AngularJS v1.2.x $digest() 无限循环指令隔离范围对象参数

AngularJS v1.2.x $digest() infinite loop Directive isolated scope object param

本文关键字:指令 无限循环 隔离 范围 参数 对象 v1 digest AngularJS      更新时间:2023-09-26

问题的简化版本,查看 Web 开发控制台:http://plnkr.co/edit/3wKmWz?p=preview

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations:

那么,为什么将对象传递到具有隔离作用域的指令中会导致无限$digest()循环呢?

// controller
// AngularJS 1.2.x infinite digest caused when returning object into directive
$scope.ctrlObjReturnFn = function() {
  return {test:true};
}
// view
<div test-dir breaking-object="ctrlObjReturnFn()"></div
// directive
app.directive('testDir', function() {
  return {
    scope: { breakingObject: '=' },
    link: function(scope, element, attrs) {
      element.html('printed obj: ' + scope.breakingObject.toString());
    }
  }
});

这是因为您将函数作为 2 路绑定传递到指令中,这不是您应该做的,要么使用 2 路绑定传递对象:

scope: { breakingObject: '=' },
<div test-dir breaking-object="ctrlObjReturnFn"></div>
$scope.ctrlObjReturnFn =  {test:true};

或使用 1 路绑定的函数:

scope: { breakingObject: '&' },
<div test-dir breaking-object="ctrlObjReturnFn()"></div>
$scope.ctrlObjReturnFn = function() {
   return {test:true};
}

见扑通。