StackOverflow_23064048: passing-a-controller-function-between-directives
Illustration of answer to http://stackoverflow.com/questions/23064048/passing-a-controller-function-between-directives.
by ExpertSystem
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-controller="myCtrl">
<item-list items="data" functionreference="controllerfunction(name)"></item-list>
<button ng-click="controllerfunction('Test')">Test controllerfunction</button>
</div>
CSS
li {
border: 1px solid;
padding: 5px;
margin: 5px;
}
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('itemList', function ($compile) {
return {
restrict: 'E',
template: '<ul><item ng-repeat="item in items" item="item" functionreference="functionreference({name: name})"></item></ul>',
scope: {
items: '=',
functionreference: '&'
}
};
});
myApp.directive('item', function ($compile) {
return {
restrict: 'E',
scope: {
item: '=',
functionreference: '&'
},
link: function ($scope, $element, $attrs) {
$scope.directivefunction = function (name) {
alert("directivefunction: " + name); // DOES work
$scope.functionreference({name: name}); // Does NOT work
};
$element.append('<li>{{item.name}} [ ' +
'<a href="#" ng-click="directivefunction(item.name)">directivefunction</a> / ' + // DOES work
'<a href="#" ng-click="functionreference({name:item.name})">functionreference</a>]' + // Does NOT work
'<item-list items="item.children" functionreference="functionreference({name:name})"></item-list></li>');
$compile($element.contents())($scope.$new());
}
};
});
myApp.controller('myCtrl', function ($scope) {
$scope.controllerfunction = function (name) {
alert("controllerfunction: " + name);
}
$scope.data = [
{ name: 'Group 1',
children: [
{ name: 'Sub 1.1',
children: [
{ name: 'Child 1.1.1'},
{ name: 'Child 1.1.2'}
] },
{ name: 'Sub 1.2',
children: [
{ name: 'Child 1.2.1'},
{ name: 'Child 1.2.2'}
] }
] },
{ name: 'Group 2',
children:...