2

I've seen the many, many, many, many questions on this problem but for some reason I still can't bind ng-click in my directive to a method on the parent controller. I'm pretty sure I've got my scope isolation and method parameter passing right but no luck so far. A gross simplification (this app is huge) of my JS looks like this:

angular.module('myApp', []);

angular.module('myApp').directive('myCustomDirective', customDirective);

function customDirective() {
  return {
    restrict: 'E',
    scope: {
      myCallback: '&myCallback'
    }
    template: '<div><h3>My directive</h3><p>I am item {{itemIndex}}</p><button ng-click="myCallback({itemIndex: itemIndex})">Click to call back</button></div>'
  }
}

angular.module('myApp').controller('myController', myController);

function myController() {
  var vm = this;
  vm.selectedIndex = -1;

  vm.items = [0, 1, 2, 3, 4];

  vm.callbackMethod = function(itemIndex) {
    vm.selectedIndex = itemIndex;
  }
}

and the similarly simplified markup looks like this:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="myController as test">
      <p>Selected item: {{test.selectedIndex}}</p>
      <my-custom-directive my-callback="test.callbackMethod" ng-repeat="item in test.items" ng-init="itemIndex = $index"></my-custom-directive>
    </div>
  </body>

</html>

I'm at a loss here as I've followed every SO post and blog on the subject and still nothing. Just to make things worse, the Plunk I made to illustrate this problem also doesn't work ($injector:nomod) - bonus points if anyone can spot why! ;-)

Community
  • 1
  • 1
Mourndark
  • 2,526
  • 5
  • 28
  • 52

2 Answers2

2

You should define method with parameter, rather than putting it reference on directive element.

my-callback="test.callbackMethod(itemIndex)" 

Also do pass current element index to directive by adding it in isolated scope.

scope: {
  myCallback: '&myCallback',
  itemIndex: '='
},

Demo Here

Related answer

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
1

I added an extra attribute to your directive and removed the ng-init.

 <my-custom-directive my-callback="test.callbackMethod($index)" ng-repeat="item in test.items track by $index" theindex="$index"></my-custom-directive>

Example

Ashkan Hovold
  • 898
  • 2
  • 13
  • 28