Angularjs指令双向绑定变量更改不会在父作用域

时间:2016-08-05 20:12:28

标签: angularjs angularjs-directive angular-digest

道歉,如果某些JS在语法上是关闭的。我是在看着我的CoffeeScript

时写的

我有一个文本编辑器,我已经将其提取到一个指令中,我想在它和它包含的模板之间共享一些状态:

主要包含模板



<div class="content">
  <editor class="editor" ng-model="foo.bar.content" text-model="foo.bar"></editor>
</div>
&#13;
&#13;
&#13;

模板控制器

&#13;
&#13;
angular.module('foo').controller('fooController', ['$scope', ... , function ($scope, ...) {
  $scope.foo = {}
  $scope.foo.bar = {}
  $scope.foo.bar.content = 'starting content'
  
  $scope.$watch('foo.bar', function () { 
    console.log('content changed')
  }, true)
}
&#13;
&#13;
&#13;

模板双向使用编辑器指令绑定其范围对象$scope.foo.bar。当文本发生变化时,编辑的文字改变了&#39;触发处理程序并更改绑定对象上的属性。

编辑指令

&#13;
&#13;
angular.module('foo').directive('editor'), function (
  restrict: 'E',
  templateUrl: 'path/to/editor.html',
  require: 'ng-model',
  scope: { 
   textModel: '='
  },
  controller: [ 
      ...
      $scope.editor = 'something that manages the text'
      ...
  ],
  link: function (scope, ...) {
    scope.editor.on('text-change', function () {
      $scope.textModel.content = scope.editor.getText()
      
      // forces parent to update. It only triggers the $watch once without this
      // scope.$parent.$apply()
    }
  }
&#13;
&#13;
&#13;

然而,在指令中更改此属性似乎没有达到我在foo.bar上设置的深度$ watch。经过一番挖掘,我能够使用指令的父引用来强制$ digest周期scope.$parent.$apply()。我真的不应该这样做,因为该属性是共享的,应该自动触发。为什么它不会自动触发?

以下是我遇到的一些相关的好读物:
$watch an object
https://www.sitepoint.com/understanding-angulars-apply-digest/

1 个答案:

答案 0 :(得分:1)

on函数是jqLit​​e / jQuery函数。它不会触发消化循环。它基本上超出了角度的意识。您需要使用$ apply手动触发摘要周期。