Select 2 with tags, query function not defined inside custom directive
When using the UI Select2 directive with tags on an input field, if the input itself is inside a custom directive then it is not initialised correctly and the console gives an error:
query function not defined for Select2 tagging
I suspect this might be to do with the order in which the directives are compiled / linked vs when the select 2 function is called.
Maybe there is a simple workaround, perhaps using the compile function or a directive controller instead of a link function? Or maybe it is an issue with the Angular UI select2 directive.
I have made a plunker that displays the problem:
http://plnkr.co/edit/myE5wZ
And an SO question:
http://stackoverflow.com/q/15633365/1796763
Any help on how to get select2 tagging working inside a custom directive is much appreciated. Thanks.
Found a workaround:
If you define the variables on the controller scope, and then pass them into the directive it works.
http://plnkr.co/edit/oHAWrK
So I think this is to do with when things are available on the scope, the link function is clearly not the right the place to do this. I would ideally still like a solution where I could encapsulate the select2 options inside the scope, instead of having to define everything in the parent controller if anyone knows how to do this?
In the end I managed to find a solution I was happy with involving nesting two directives, that way the logic can be encapsulated inside the parent directive (not spilling out into the controller).
A Plunker of my solution is here for anyone who may stumble across the same requirement:
http://plnkr.co/edit/ZxAPF5BzkgPtn9xddCRM
For anyone wondering why this demo isn't working on Chrome, it's because the 'index.html' file includes scripts from raw.github.com, that sends them with mime type 'text/plain', which Chrome won't execute. It's easy to solve, just change all references from raw.github.com to rawgithub.com
@dutzi you're awesome. I didn't know about that site!
Moving the select2 option objects into the directive controller (rather than link) function seems to work, which is simpler than your nested directive solution.