Angular - 对指令控制器范围的更改未反映在视图中

Angular - changes to directive controller's scope aren't reflected in view

我的范围变量 foo 的更改正在 html 中更新。当该值在指令控制器的范围内更改时,它不会在 html.

中更新

我需要做什么才能让它更新?

我有一个简单的example

app.js

var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
  $scope.foo = 99;

  $scope.changeValue = function() {
    $scope.foo = $scope.foo + 1;
  }
});

app.directive('d1', function(){
  return {
    restrict: 'E',
    scope: {
      theFoo: '='
    },
    templateUrl: 'd1.html',
    controller: 'd1Ctrl',
  }
});

app.controller('d1Ctrl', function($scope) {
  $scope.test = $scope.theFoo;
});

d1.html

<div>
  <p>The value of foo is '{{theFoo}}'.</p>
  <p>The value of test is '{{test}}'.</p>
</div>

inside index.html

<d1 the-foo='foo'>
</d1>

<button ng-click='changeValue()'>change value</button>

总之,{{theFoo}} 正在更新,但 {{test}} 没有。为什么?

如果在 link 编辑控制器时确实设置了该值,则您控制器中的代码只会初始化为该值。任何后续更改都不会起作用。

如果您想绑定任何后续更改,则需要在控制器或 link 函数中设置 $watch 语句。

$scope.$watch( 'theFoo', function(val){ $scope.test = val; })

更新了 plunker - http://plnkr.co/edit/eWoPutIJrwxZj9XJu6QG?p=preview

原因是$scope.foo值是原始值。

在指令控制器中,您只在控制器初始化时分配 $scope.test 一次。基元没有像对象那样的继承方式,因此在初始分配

之后没有任何变化 $scope.test

如果您使用对象而不是传入...继承将生效并且您会看到更改...否则您将需要观察 $scope.theFoo 并更新 $scope.test你自己

这里你已经隔离了指令的范围,所以 testd1.html 是不可见的,如果你需要改变 test 连同 theFoo您必须首先通过

使其对指令可见
app.directive('d1', function(){
  return {
    restrict: 'E',
    scope: {
      theFoo: '=',
      test : '=' //getting test as well
    },
    templateUrl: 'd1.html',
    controller: 'd1Ctrl',
  }
});

在 index.html 中,您应该将值传递给测试 <d1 the-foo='foo' test='foo'></d1>

在上面的代码中你的控制器没有多大用处,即使没有这部分代码也能正常工作 controller: 'd1Ctrl'。 使用此示例,您不必使用 $watch.