[英]Angular JS directive, change a 2 way data binding in the link function
我正在嘗試創建一個角度指令,我可以在其中通過單個選項對象或某些屬性設置選項。 下面是這種代碼的一個例子:
app.directive('testElement', [function () {
return {
restrict: "E",
scope: {
options: "="
},
template: "<p><span>Name: </span>{{ options.name }}</p>",
link: function (scope, element, attrs) {
scope.options = scope.options || {};
if (attrs.name)
scope.options.name = attrs.name;
}
};
}]);
這很好用,因為如果我通過 options 屬性傳入名稱,則會顯示名稱值。 但是,如果我通過 name 屬性傳遞名稱,即使鏈接函數確實修改了選項,也不會呈現該值。
http://plnkr.co/edit/IMVZRdAW2a5HvSq2WtgT?p=preview
我覺得我在選項的 2 方式數據綁定如何工作方面缺少一些基本的東西。
如果不通過雙向數據綁定,angular 會生氣:
https://github.com/angular/angular.js/issues/1435
使用可選綁定 (=?):
app.directive('testElement', [function () {
return {
restrict: "E",
scope: {
options: "=?"
},
template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
link: function (scope, element, attrs) {
scope.options = scope.options || {};
if (attrs.name)
scope.options.name = attrs.name;
}
};
}]);
或者,如果您使用的是舊版本的 angular,請在 attrs 上使用 $eval。 選項:
app.directive('testElement', [function () {
return {
restrict: "E",
//Still can create isolate scope to not clobber parent scope variables.
scope: {},
template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
link: function (scope, element, attrs) {
scope.options = scope.$eval(attrs.options) || {};
if (attrs.name)
scope.options.name = attrs.name;
}
};
}]);
該指令需要一個選項參數。 在第二種情況下你沒有提供它,因此有一個錯誤
如果隔離范圍變量是可選的,則使用?
喜歡
scope: {
options: "=?"
}
查看我的 plunkr http://plnkr.co/edit/eGh6r1X7HzY1sZIDYZ69?p=preview
和有關隔離范圍的文檔http://docs.angularjs.org/api/ng/service/ $compile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.