You can $ pass events to child areas (as mentioned), or you can also add a function to the parent directory controller from your child directive.
Here is jsfiddle with examples of the $ broadcast to child directive and using the controller technique.
angular.module("myApp", []) .directive("parentDirective", function () { var directive = {}; directive.restrict = "E"; directive.scope = {}; directive.template = '<div>' + '<button type="button" ng-click="broadcastDemo()">' + 'Broadcast to child' + '</button>' + '<button type="button" ng-click="controllerDemo()">' + 'Use Controller' + '</button><br /><br />' + '<child-directive></child-directive>'; //Setup directive controller directive.controller = function ($scope) { var ctrl = this; //Store events for convenience var events = ctrl.events = { setPlaceHolderText: "setPlaceHolderTextEvent" }; $scope.broadcastDemo = function () { //$broadcast event and optional additional args $scope.$broadcast(events.setPlaceHolderText, "Additional arg1", "Additional arg2"); }; $scope.controllerDemo = function () { //do some work //call the ctrl.setPlaceHolderText added by child if (ctrl.setPlaceHolderText) { ctrl.setPlaceHolderText(); } }; }; return directive; }) .directive("childDirective", function () { var directive = {}; directive.restrict = "E"; directive.scope = {}; directive.require = ["^parentDirective", "?ngModel"]; directive.template = '<div></div>'; directive.link = function (scope, elem, attrs, ctrl) { var parentDirCtrl = ctrl[0]; //allow parent scope(s) to $broadcast event scope.$on(parentDirCtrl.events.setPlaceHolderText, function (event, arg1, arg2) { elem.html("$Broadcast: " + arg1 + " " + arg2); }); //Add function to parent controller parentDirCtrl.setPlaceHolderText = function () { elem.html("Added to parent controller!"); } }; return directive; });
If you have several child directives and you add a function to the parent directory controller, you will have to take precautions because each additional child directive will compress ctrl.setPlaceHolderText (i.e. only one elem.html will be called).
The bindonce library uses something similar to the second method, allowing child directives to add βbindersβ to the parent directive. The released model is probably cleaner for your purposes, but wanted to provide another option for directory communication.
Patrick
source share