从子指令更新父范围

Update the Parent Scope from Child Directive

就在我认为自己掌握了 AngularJS 的时候,它让我落伍了。我试图通过将父范围中的值传递到一个独立的范围来更新父范围中的值,然后在那里更新它。

我认为使用两种方式的数据绑定会像下面这样简单:

在父控制器中:

var self = this;
self.variable = 'Init';

在元素中:

<div data-example-directive data-variable="ParentCtrl.variable"></div>

在子指令中:

scope: {
    variable: '='
}
link: function(scope) {

    scope.updateVal = function(updatedVal) {
        scope.variable = updatedVal;
    }
}
template: '<button ng-click="updateVal('Updated Value')"></button>'

现在,如果在该函数内,我在 scope.variable 上调用 console.log,它会显示 updatedVal 的正确值。但是在页面本身上,父级尚未更新。有什么需要我打电话的 "refresh" 吗?

我认为 AngularJS 的要点是内置了双向数据绑定,我不必要求它根据以后的逻辑更新值?有同事用过 broadcast 但有没有更优雅的解决方案?

你的问题很简单:

当您阅读时: 在您的范围内您还没有 variable,因此 angular 将尝试查看父级,等等...直到它找到了。

当你写 : 时,它会在你当前的范围内设置 variable。但是你的父范围仍然有旧的 variable,你没有更新它,因为 variable 不直接在你当前的范围内。

看看:

您可以使用圆点表示法解决这个问题。使用 controller as 语法的示例:

<div ng-controller="controller1 as controller1">
    {{controller1.variable}}
    <div ng-controller="controller2 as controller2">
        <input ng-model="controller1.variable" type="text"/>
    </div>
</div>

你在controllerAs风格和$scope风格中完成了一半,你需要选择一个。既然另一个答案是前者,我就做后者(这个我比较熟悉;p)

angular.module('test', [])

.directive('exampleDirective', function() {
  return {
    scope: {
      variable: '='
    },
    link: function(scope) {
      scope.updateVal = function(updatedVal) {
        scope.variable = updatedVal;
      }
    },
    template: '<button ng-click="updateVal(\'Updated Value\')">Update</button>'
  }
})

.controller('Test', function($scope) {
  $scope.variable = "Init";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app='test' ng-controller="Test">
  {{variable}}
  <div data-example-directive data-variable="variable"></div>
</body>