2015-02-12 136 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