3

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);
}
Community
  • 1
  • 1
iamsar
  • 1,080
  • 2
  • 15
  • 28

1 Answers1

4

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()"
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • I knew it had to be something simple. Didn't think it'd be as easy as adding parenthesis. Thanks. – iamsar Nov 21 '13 at 15:28