[英]Directive binding with AngularJS
我在AngularJS中創建了一個自定義指令。 在鏈接函數中,我將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;
});
我不明白你為什么需要在link func中設置屬性。 您只需輸入模板即可。
http://plnkr.co/edit/9u6nkLYKHxBBiJ60mpbF?p=preview
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;
});
您可能想要詳細說明您真正想要實現的目標。
如果要在鏈接函數中修改模板,則必須重新編譯它。
解決方案: 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元素/樹)綁定到范圍
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.