daydreamer
daydreamer

Reputation: 92149

Angular Directive throws $digest already in progress when trying to call controller method

Here is my plunker - http://plnkr.co/edit/VYH5QbO99ZbMkvc2D4Fe?p=preview

UPDATE
The body of HTML in firebug looks like

<body data-ng-controller="SummaryController" class="ng-scope">
    <h1>Hello Directive!</h1>
    <ng-view></ng-view>
    <div summary="loadPie1()">
     <div>
      <div id="pie1">I am pie 1</div>
      <div id="pie2">I am pie 2</div>
     </div>
    </div>
</body>

Please help

Upvotes: 1

Views: 3663

Answers (1)

galchen
galchen

Reputation: 5290

Your scope.$apply is not needed there. The link function is called and the template is built with the scope, so you are trying to apply scope changes for template that is being built

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

One way to solve it is:

app.directive('summary', function(){
  return {
    restrict: 'A',
    scope : {
       summary : '='
    },
    templateUrl: 'summary.html',
    link: function(scope, elem, attrs){
      console.log('directive: call to load pie1');
      scope.summary();
    }
  }
});

app.controller('SummaryController', function($scope){
  console.log('controller glued');
  $scope.loadPie1 = function() {
        console.log('controller: will load pie1');
  };
});


<div summary="loadPie1"></div>

You can pass the actual function closure, instead of a string

Upvotes: 1

Related Questions