Angularjs指令隔离范围+单向数据绑定不适用于对象?

mur*_*308 11 javascript data-binding angularjs angularjs-directive

我创建了一个具有两个值的自定义指令.第一个是配置对象,第二个是数据对象.我在我的指令中修改了这个配置和数据对象,这反映在父范围内.当我不得不多次使用指令时,这会导致错误.

我跟着https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/,我正在使用隔离范围.

我想在隔离范围内为对象提供单向数据绑定.无论我在指令函数中改变什么,它都不应该反映在父范围内.

以下是指令范围.

scope: {
    config: "&config",
    dataObj: "&dataObj"
}
Run Code Online (Sandbox Code Playgroud)

这是我如何在指令的link函数中访问它

var config = scope.config();
var dataObj= scope.dataObj();
Run Code Online (Sandbox Code Playgroud)

我假设通过引用传递发生在这里.

我正在添加JSbin.检查控制台对象的值是否正在改变并反映在父范围内.

https://jsbin.com/vagowe/edit?html,js,output

Pav*_*ala 19

传递文本是one-way binding(@)和传递对象是two-way binding(=)

将对象作为文本传递

<custom-directive config="{{config}}"></custom-directive>
Run Code Online (Sandbox Code Playgroud)

指令范围

scope: {
  config: "@"
}
Run Code Online (Sandbox Code Playgroud)

将字符串转换回链接中的对象

var config = angular.fromJson(scope.config);
Run Code Online (Sandbox Code Playgroud)

  • 现在有一个单向绑定以及```scope:{config:'<'}``` (8认同)
  • 这是解决这个问题的唯一方法吗? (2认同)

小智 6

你是对的,问题是你的JavaScript对象是通过引用传递的.使用单向绑定复制引用,但引用仍将指向同一对象.

我对Angular docs for directives的印象一直是:

  • '@'绑定用于插值字符串
  • '='绑定适用于应在范围之间共享的结构化数据
  • '&'绑定用于重复执行绑定到父作用域的表达式

如果要将父对象中的绑定对象视为不可变对象,可以使用angular.copy创建链接代码中对象的深层复制:

var config = angular.copy(scope.config());
var dataObj = angular.copy(scope.dataObj());
Run Code Online (Sandbox Code Playgroud)

或者,您可以为此使用双向绑定,并以相同的方式复制对象:

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);
Run Code Online (Sandbox Code Playgroud)