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