AngularJS v1.2.x $digest() infinite loop Directive

2019-07-20 21:11发布

问题:

Simplified version of problem, view web dev console: http://plnkr.co/edit/3wKmWz?p=preview

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

So why does passing an object into a directive with an isolated scope cause an infinite $digest() loop?

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

回答1:

This is because you're passing in a function as a 2 way binding into the directive, which is not what you should be doing, either pass an object using 2 way binding:

scope: { breakingObject: '=' },

<div test-dir breaking-object="ctrlObjReturnFn"></div>

$scope.ctrlObjReturnFn =  {test:true};

or a function using 1 way binding:

scope: { breakingObject: '&' },

<div test-dir breaking-object="ctrlObjReturnFn()"></div>

$scope.ctrlObjReturnFn = function() {
   return {test:true};
}

See plunk.