用AngularJS绑定指令
Directive binding with AngularJS
我在AngularJS中创建了一个自定义指令。在link函数中,我将ng-model和ng-options属性添加到内部模板中,但不幸的是,绑定不起作用。但是当我把内部模板放入我的html文件时,一切都工作得很好。
application.directive("customSelect", function () {
var directive = {
restrict: 'E',
template: '<select name="ArrDeplocation" class="arrdepSelect"></select>',
link: function (scope, elem, attr) {
console.log('scope: ', scope);
console.log('element: ', elem);
console.log('attribute: ', attr);
$(elem.children()[0]).attr('ng-model', 'model.selectedCity');
$(elem.children()[0]).attr('ng-options', 'city for city in model.cities');
$(elem.children()[0]).selectmenu();
}
};
return directive;
});
我不明白为什么你需要在链接函数中设置属性。你可以简单地把它放到你的模板中。
http://plnkr.co/edit/9u6nkLYKHxBBiJ60mpbF?p =
预览app.directive("customSelect", function () {
var directive = {
restrict: 'E',
template: '<select name="ArrDeplocation" class="arrdepSelect"'
+ 'ng-model="model.selectedCity" ng-options="city for city in model.cities"> </select>',
link: function (scope, elem, attr) {
// run jquery mobile methods here...
}
};
return directive;
});
你可以在这里详细说明你真正想要达到的目标。
如果你想在link函数中修改你的模板,那么你必须重新编译它
解决方案:http://plnkr.co/edit/bpiqXdQe91RJBaJXTPXO?p=preview
app.directive("customSelect", function ($compile) {
return {
restrict: 'E',
template: '<select name="ArrDeplocation" class="arrdepSelect"></select>',
link: function (scope, elem, attr) {
elem.find('select').attr({
'ng-model': 'model.selectedCity',
'ng-options': 'city for city in model.cities'
});
var tpl = elem.html();
elem.html($compile(tpl)(scope));
elem.find('select').selectmenu();
}
};
});
$compile("html string")
将模板编译为:
一个链接函数,用于将模板(DOM元素/树)绑定到作用域
相关文章:
- 将指令绑定到控制器属性
- 角度指令:绑定'鼠标悬停'事件添加到元素
- 离子/角度指令绑定到滚动
- ng使用UI引导指令绑定html
- angularjs指令绑定带参数的函数
- 单元测试 Karma Jasmine 语法错误:在“&”角度指令绑定上解析错误
- 角度指令绑定到元素的高度
- 将 AngularJS 指令绑定到元素
- 角度指令绑定
- 将属性从一个指令绑定到另一个指令
- AngularJS多个动态指令绑定
- 在AngularJS中,如何将指令绑定到指令以外的元素中's根元素
- 调用与angular指令绑定的参数化函数
- 指令绑定中的值是正确的,但它'It’’It’这不是真的
- AngularJS指令绑定链接:无法访问作用域变量
- 如何使选项从选择指令绑定到另一个数组
- 把一个指令绑定到另一个指令里的方式是什么?
- 如何将控制器中的指令绑定到HTML中
- AngularJS指令绑定
- 访问指令绑定到的元素