为什么在链接中更改父指令作用域的值不会向子指令提供该突变状态?



我有一个父指令,它被传递给一个数组作为其一个属性的值。父指令的工作是呈现一些组件,然后将该数组的修改版本发送给子指令。然后,子指令需要呈现修改后的数组。

在父指令的链接函数中调整此数组似乎不会将更改传播到所呈现的子指令。

为什么会这样?

我对AngularJS只有几天的了解,可能对范围或生命周期有根本的误解,尽管我不确定是哪一个。

下面的示例通过将父指令推入3来修改提供给父指令的[1,2]数组。

父指令提供了一个模板,其中包含子指令,以及我所希望的突变数组。

屏幕将呈现未变异的数组(从子指令呈现(,但console.log会呈现变异的数组,(从父指令记录(

https://codesandbox.io/s/trusting-fire-k4so0?fontsize=14&隐藏导航=1&主题=深色

src/index.js

"use_strict";
var angular = require("angular");
angular
.module("App", [])
.controller("IgnorableController", [function(){}])
.directive("parentIsolatedScope", [
function() {
return {
restrict: "E",
template:
"<child-isolated-scope mutated-array='mutableArray'></child-isolated-scope>",
scope: {
mutableArray: "<"
},
link: function(scope) {
scope.mutableArray.push(3);
console.log(scope.mutableArray);
}
};
}
])
.directive("childIsolatedScope", [
function() {
return {
restrict: "E",
template: "<div>{{mutatedArray | json}}</div>",
scope: {
mutatedArray: "<"
}
};
}
]);

index.html

<!DOCTYPE html>
<html ng-app="App">
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script src="src/index.js"></script>
</head>
<body ng-controller="IgnorableController">
<parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>
</body>
</html>

如果为初始数组声明一个变量,并使用它将数组传递到指令中,它将按预期工作。

你能解释一下为什么会这样吗?

<body ng-controller="IgnorableController">
<parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>
</body>

当绑定是解析为数组的AngularJS表达式时,在每个摘要循环中,框架都会评估该表达式,并将隔离范围变量设置为该值。在每个消化周期中,框架都会重新设置值,以取代任何突变。

带变量:

<body ng-controller="IgnorableController" ng-init="x = [1,2]">
<parent-isolated-scope mutable-array="x"></parent-isolated-scope>
</body>

对变量的引用被指定给隔离作用域。

请注意,引用内容的任何突变都会更改子隔离范围和父范围中的内容。这可能会对某些设计产生意想不到的后果。

如果您为初始数组声明一个变量,并使用它将数组传递到指令中,它将按预期工作:

<body ng-controller="IgnorableController">
<parent-isolated-scope mutable-array="initialArray"></parent-isolated-scope>
</body>

在IgnorableController中,数组变量:

$scope.initialArray= [1, 2];

工作演示:演示

最新更新