AngularJS指令双向绑定的变量更改不会触发父作用域上的$digest。
AngularJS指令双向绑定的变量更改不会触发父作用域上的$digest。
抱歉如果一些JS的语法有误。我在查看我的CoffeeScript时编写的。\n我有一个文本编辑器,我已经将其提取为一个指令,我想在它和包含的模板之间共享一些状态:\n主要包含模板\n
\n模板控制器\n
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) }]
\n模板双向绑定在其作用域对象`$scope.foo.bar`上,使用编辑器指令。当文本改变时,编辑器的\'text-change\'处理程序被触发,并更改了绑定对象上的属性。\n编辑器指令\n
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() // 强制父级更新。如果没有这个,只会触发一次$watch // scope.$parent.$apply() } }]
\n然而,在指令中更改此属性似乎没有触发我在`foo.bar`上设置的深度$watch。经过一些调查,我能够使用指令的父级引用来强制执行$digest周期`scope.$parent.$apply()`。但是实际上我不应该需要这样做,因为属性是共享的,应该自动触发。为什么不会自动触发呢?\n以下是我遇到的一些相关的好文章:\n[https://stackoverflow.com/questions/19455501/watch-an-object](https://stackoverflow.com/questions/19455501/watch-an-object)\n[https://www.sitepoint.com/understanding-angulars-apply-digest/](https://www.sitepoint.com/understanding-angulars-apply-digest/)
AngularJS指令的双向绑定变量更改不会触发父作用域上的$digest的问题,其原因是on
函数是一个jqLite/jQuery函数,它不会触发脏检查循环(digest cycle)。它基本上处于Angular的意识之外。因此,需要手动触发脏检查循环,使用$apply方法。
解决这个问题的方法是,使用$apply方法手动触发脏检查循环。下面是代码示例:
angular.module('myApp').directive('myDirective', function() { return { restrict: 'E', scope: { myVar: '=' }, link: function(scope, element, attrs) { element.on('click', function() { // 修改双向绑定变量 scope.myVar = 'newValue'; // 手动触发$apply scope.$apply(); }); } }; });
在上述代码中,我们定义了一个指令myDirective
,它具有一个双向绑定变量myVar
。在指令的link
函数中,我们给元素绑定了一个click
事件,当点击元素时,修改了myVar
的值,并手动触发了$apply
方法。
通过这种方式,我们可以确保当双向绑定变量myVar
发生变化时,父作用域上的$digest循环会被正确地触发,从而更新视图。