2015-02-12 84 views
0

我正在触发事件。它的事件监听器是在指令的控制器内部定义的。控制器在事件触发后执行,因此事件侦听器代码不会执行。事件侦听器在触发事件后执行

//HTML code 
<div class="container" ng-controller="ServerController"> 
    <notification position="top" timeout="5000" class="myClass"> </notification> 
</div> 

控制器 -

if (appUtils.groupCreated === true) { 
     console.log("inside"); //getting printed 
     $rootScope.$broadcast("notifyEvent", { 
      type: "alert-success", 
      message: "Server group is successfully created." 

     }); 
     appUtils.groupCreated = false;   
}; 

通知指令 -

.directive("notification", function($interval) { 
return { 
restrict: "E", 
scope: { 
    timeout: "@", 
    position: "@" 
}, 
replace: true, 
template: '<div><div ng-repeat="notification in notifications" ng-show="displayNotification" class="alert alert-dismissible {{notification.type}} {{notificationPosition}}" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>{{notification.message}}</div></div>', 
controller: function($scope) { 
    console.log("notification"); 
    $scope.$on("notifyEvent", function(e, notifyObject) { 
     $scope.displayNotification = true; 

     // if there are multiple messages 
     if (notifyObject.messages && notifyObject.messages.length > 0) { 
      $scope.notifications = notifyObject.messages; 
     } else { 
      $scope.notifications = [{ 
       message: notifyObject.message, 
       type: notifyObject.type 
      }]; 
     } 


     if ($scope.position) { 
      $scope.notificationPosition = "notify" + $scope.position; 
     } 

     if ($scope.timeout) { 
      $interval(function() { 
       $scope.displayNotification = false; 
      }, $scope.timeout); 
     } 
    }); 
}, 
link: function(scope, element, attributes, controller) { 
    scope.timeout = attributes.timeout; 
    scope.position = attributes.position; 
} 

} });

控制台语句的顺序是 - 内部,inside1然后通知

+0

是控制器的片段上ServerController NG-init事件执行? – Michael 2015-02-12 09:11:50

+0

@MichaelZucchetta - No – 2015-02-12 09:15:29

+0

标题与文本冲突。 – Teemu 2015-02-12 09:15:50

回答

0

会发生什么:

  • 服务器控制器首先实例化然后
  • 你的指令控制器实例化
  • 你的指令postLink功能执行

Perh aps使您的ServerController成为来自postLink函数的指令和$广播。默认情况下,指令的链接功能是后链接功能。当编译器穿过你的DOM节点,从父母到孩子:

  • 控制器首先实例化的道路上下来
  • 预链接功能上下来
  • postLink功能在途中时执行的方式执行

Directive controller and link timing in AngularJS