How to write a complex custom directive