Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs: call function from directive attribute

This seems simple enough and I have it working to some degree but there's some issues with my solution.

The scenario is that I want to pass a function (toggleValue()) to a directive and then call that function via ngChange from within the directive template. The basic setup is:

// html
<div class="my-directive" ng-model="my_model" ng-change="toggleValue()"></div>

// angular directive
myApp.directive('myDirective', function() {
  return {
      scope: {
        restrict: 'C',
        model: '=ngModel',
        action: '=ngChange'
      },
      template: '<input type="checkbox" ng-model="model" ng-change="action">'
  }
}

This is a bit over-simplified since it's out of context but it demonstrates what I'm trying to do. This also works. The issue with it is that it gets called several times -- even before it's explicitly called. This appears to be due to the 2-way binding on the action. As I understand, & should be used for isolating methods but when I change action to '&ngChange' the function, toggleValue(), never gets called at all.

I tried incorporating the solution at Call a controller function from a directive without isolated scope in AngularJS but didn't have any success. Using $apply() gave me a $digest error and using $eval() had no response.

link: function (scope, element, attrs) {
  scope.$eval(attrs.action);
}
like image 619
iamsar Avatar asked Nov 24 '25 13:11

iamsar


1 Answers

To pass a function, you need to use & not = in the scope definition:

action: '&ngChange'

Then you need to call the action in the directive template:

ng-change="action()"
like image 134
Davin Tryon Avatar answered Nov 26 '25 06:11

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!