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);
}

1 Answer 1

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()"
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it had to be something simple. Didn't think it'd be as easy as adding parenthesis. Thanks.

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.