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

问题描述 投票:0回答:2

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

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

这是为什么?

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

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

parent指令呈现了一个模板,其中包含child指令,以及我希望成为的变量数组。

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

https://codesandbox.io/s/trusting-fire-k4so0?fontsize=14&hidenavigation=1&theme=dark

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>
angularjs angularjs-directive angularjs-scope
2个回答
0
投票

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

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

在IgnorableController中,数组变量:

$scope.initialArray= [1, 2];

工作演示:DEMO


0
投票

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

您能解释为什么会这样吗?

<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>

对变量的引用已分配给隔离范围。

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

© www.soinside.com 2019 - 2024. All rights reserved.