Search Posts

Use ng-model to avoid $digest delay in Component Directives

How to call controller’s any function in directive in angularJs

I’m trying to call parent controller’s function, which has not much to do with the directive, when directive’s bind value has changed.

I’ve been looking through the Q&A in stack, but all of them are related to passing a value from directive to controller, which is not my case.

I thought my case was generally common, the scenario is that:
display complex objects in a loop, one of property of object bind on a directive. and when the property has changed, do-something with the updated complex object.

However in my code, it prints the old object value instead of updated one. My guess is that my update function is called before $digest process has completed.

any suggestions?

plunker example: https://plnkr.co/edit/bWGxEmJjNmiKCkRZTqOp?p=preview

here is the Controller code:

  var $ctrl = this;
  $ctrl.items = [
      {id: 1, value: 10}, {id: 2, value: 20}, {id: 3, value: 30}
  ];

  $ctrl.update = function(item){
    //trying to update item after changing
    console.log("updated item is: " + angular.toJson(item));
  };

Here is the directive code:

var controller = function($scope){
   var $ctrl = this;
   $ctrl.clicked = function(){
      $ctrl.value = $ctrl.value + 1;

      //calling the bind on-change function defined in controller
      $ctrl.onChange();
   }
};

return {
   restrict: 'E',
   scope: {
          value: '=',
          onChange: '&'
   },
   controller: controller,
   controllerAs: '$ctrl',
   bindToController: true,
   templateUrl: 'directive.html'
};

and Html looks like this:

<div ng-repeat="item in mc.items">
  <my-directive value="item.value" on-change="mc.update(item)"></my-directive>
</div>

and directive template:

<button type="button" ng-click="$ctrl.clicked()">{{$ctrl.value}}</button>

Source: AngularJS

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.