0

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.

  • Simply put a breakpoint inside the `controller` of directive. I believe the `appController` is loaded before the directive is created. By putting a timeout you just delay the event till the next digest cycle, by that time the directive is setup. – Chandermani Apr 02 '15 at 14:44
  • Yes `appController` will be executed first and then directive controller is call. This is where i am getting the problem. My event is raised even before test directive `controller` is getting executed. That's why i am delaying my raise event using $timeout event. – Jagadish Dharanikota Apr 03 '15 at 15:37

0 Answers0