【问题标题】:Angularjs directive two-way bound variable changes are not triggering $digest on the parent scopeAngularjs 指令双向绑定变量更改不会在父范围内触发 $digest
【发布时间】:2016-12-12 08:03:21
【问题描述】:

如果某些 JS 在语法上不正确,我们深表歉意。我一边看我的 CoffeeScript 一边写的

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

主要包含模板

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

模板控制器

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

模板使用编辑器指令双向绑定其范围对象$scope.foo.bar。当文本改变时,编辑器的“text-change”处理程序被触发并且绑定对象的一个​​属性被改变。

编辑指令

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()
    }
  }

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

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

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-digest


    【解决方案1】:

    on 函数是一个 jqLit​​e/jQuery 函数。它不会触发摘要循环。它基本上在 Angular 的意识之外。您需要使用 $apply 手动触发摘要循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 2014-05-18
      • 2015-10-29
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      相关资源
      最近更新 更多