I have a requirement like i want to emit an event from a controller and the event handler is present in directive controller (i.e child controller).
Please find the code below:
<div ng-app="myApp" ng-controller="appController">
<div test></div>
</div>
/* Fiddle to call views directive event from the view controller */
var app = angular.module('myApp', []);
app.controller('appController', function ($scope, $timeout) {
console.log('Inside Controller');
// If timeout is removed test-event handler will not be called as test controller is not yet executed by the time event was raised
//$timeout(function () {
$scope.$broadcast('test-event');
//});
});
app.directive('test', function () {
return {
restrict: 'A',
controller: function ($scope) {
console.log("Inside test directive controller");
$scope.$on('test-event', function () {
console.log("Test event fired");
});
}
};
});
If I un-comment $timeout in the above code, my code works fine. But i want to know some better solution rather than using above solution.
I have this scenario in my project in a view, where I have a view controller and directive with an event handler and emitting event from the view controller.