我创建了一个自定义指令属性,它将把一个普通的选择框变成一个ChosenJS (http://harvesthq.github.com/chosen/)选择框。为了使代码更简洁,我希望使用HeadJS异步加载外部chosen.js插件文件。下面是我的AngularJS指令:
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
}
})
});我遇到的问题是,因为我是异步加载的,Angular不知道它的存在,指令也不起作用。有没有办法以编程方式注入动态加载的模块指令,以便Angular知道它并相应地更新视图?
发布于 2012-09-02 08:41:18
在您的示例中,指令函数没有为指令返回配置对象,这就是它失败的原因。
试试这个:
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;
}
};
});https://stackoverflow.com/questions/12232384
复制相似问题