1

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

  • I want to keep the knowledge of controller method outside of directive so used Directive Attribute and pass controller method inside
  • Now it is failing that $digest already in progress (see console.log)

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

2
  • are you always passing a function that is defined in the scope? Commented Jun 16, 2013 at 15:31
  • yes I am doing that, and you can see that in plunker code I have shared Commented Jun 16, 2013 at 15:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

so how can I call my method loadPie1(). I used scope.$apply() by learning from egghead.io/video/LJmZaxuxlRc
This approach works, but I am not sure why approach in egghead.io/video/LJmZaxuxlRc is not working for me? the only difference is that in this video it binds mouse events and then call scope.$apply(attrs.enter)
because when you bind it, the actual event happens later. When you run scope.$apply() it executes the digest process which has not finished running during the previous compile (that initiates the directive)
@daydreamer: I was getting that error too. I fixed it by using $timeout to delay the $apply call since I wasn't doing the action later (e.g., after mouse event) as @galchen mentions. So I did this: app.directive('summary', ['$timeout', function ($timeout) { return { restrict: 'A', link: function (scope, element, attrs) { $timeout(function () { scope.$apply(attrs.summary); }, 0); }, templateUrl: 'summary.html' }; }]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.