I created a custom directive attribute that will turn an ordinary select box into a ChosenJS (http://harvesthq.github.com/chosen/) select box. To make the code cleaner, I want to load the external chosen.js plugin file asynchronously with HeadJS. Here is my AngularJS directive:
myApp.module.directive('chosen-select', function() {
head.js(myApp.pathTo.plugin.chosen);
head.ready(function() {
var linker = function(scope, element, attr) {
element.chosen();
}
return {
restrict: 'A',
link: linker
}
})
});
The problem I'm having is that it seems that because I am loading it asynchronously, Angular doesn't know it exists and the directive is not working. Is there a way to programmatically inject a dynamically loaded module directive so that Angular knows about it and can update the view accordingly?
In your example, directive function isn't returning a config object for the directive that's why it is failing.
Try this:
var myApp = angular.module('myApp', []);
myApp.directive('chosenSelect', function() {
var el;
// load chosen file
head.js(myApp.pathTo.plugin.chosen);
head.ready(function() {
jQuery(el).chosen();
});
return {
restrict: 'A',
link: function(scope, element, attr) {
// set el via closure, so that head ready callback has access to it
el = element;
}
};
});