[英]Angularjs directives isolated scope + one-way data-binding not working for objects?
我創建了一個具有兩個值的自定義指令。 第一個是配置對象,第二個是數據對象。 我在我的指令中修改了這個配置和數據對象,這反映在父范圍內。 當我不得不多次使用指令時,這會導致錯誤。
我跟着https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/ ,我正在使用隔離范圍。
我想在隔離范圍內為對象提供單向數據綁定。 無論我在指令函數中改變什么,它都不應該反映在父范圍內。
以下是指令范圍。
scope: {
config: "&config",
dataObj: "&dataObj"
}
這是我如何在指令的link函數中訪問它
var config = scope.config();
var dataObj= scope.dataObj();
我假設通過引用傳遞發生在這里。
我正在添加JSbin。 檢查控制台對象的值是否正在改變並反映在父范圍內。
傳遞文本是one-way binding(@)
,傳遞對象是two-way binding(=)
將對象作為文本傳遞
<custom-directive config="{{config}}"></custom-directive>
指令范圍
scope: {
config: "@"
}
將字符串轉換回鏈接中的對象
var config = angular.fromJson(scope.config);
你是對的,問題是你的JavaScript對象是通過引用傳遞的。 使用單向綁定復制引用,但引用仍將指向同一對象。
我對Angular docs for directives的印象一直是:
如果要將父對象中的綁定對象視為不可變對象,可以使用angular.copy創建鏈接代碼中對象的深層復制:
var config = angular.copy(scope.config());
var dataObj = angular.copy(scope.dataObj());
或者,您可以為此使用雙向綁定,並以相同的方式復制對象:
scope: {
config: "=",
dataObj: "="
}
// ...
// Inside the link function of the directive.
// Note that scope.config and scope.dataObj are no longer functions!
var config = angular.copy(scope.config);
var dataObj = angular.copy(scope.dataObj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.