I've got a ng-repeat creating multiple directives, each with an isolated scope. I want to be able to call a single function that calls a function on each directive, so it resets a variable on each isolated scope. I can't work out anyway to do this? I realise this might not be best practice, but I just need a solution at the moment.
2 Answers
Another option that i use in a similar vein is angulars event system.
I'm creating a dashboard of widgets. My widget is a directive contained within a ng-repeat.
I emit events in my controller $scope.$broadcast then listen in my directive with $scope.$on. I use the $index of the ng-repeat to be able to target specific widgets.
quick example fiddle: http://jsfiddle.net/adyjm9g4/
EDIT: Forgot to mention you can also pass data: http://jsfiddle.net/adyjm9g4/1/
Comments
A way to do it is to provide a callback to the directive (i.e. scope: { xxx: '&' }) that will execute some functionality. Could be:
<the-directive callback="ctrl.command(action, argument)" /> And the directive looks like:
app.directive('theDirective', function() { return { ... scope: { callback: '&', ... }, controller: ['$scope', function($scope) { this.resetTheVariable = function() { // DO WHAT YOU WANT HERE }; $scope.callback({ action: 'register', argument: this }); $scope.$on('$destroy', function() { scope.callback({ action: 'deregister', argument: this }); }); }] }; }) Now the controller invoking this directive would look like:
function TheController() { var registeredDirectives = []; this.command = function(action, argument) { switch(action) { case 'register': registeredDirectives.push(argument); break; case 'deregister': var index = registeredDirectives.indexOf(argument); if( index >= 0 ) { registeredDirectives.splice(index, 1); } break; } }; this.resetAll = function() { registeredDirectives.forEach(function(registeredDirectiveController) { registeredDirectiveController.resetTheVariable(); }); }; }