触发事件后执行事件侦听器

时间:2015-02-12 09:05:24

标签: javascript angularjs

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

//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;
}

}    });

控制台声明的顺序是 - inside,inside1然后是通知

1 个答案:

答案 0 :(得分:0)

会发生什么:

  • 首先实现服务器控制器
  • 然后实现您的指令控制器
  • 执行指令postLink函数

也许让你的ServerController成为一个指令,并从postLink函数广播。默认情况下,指令的链接功能是一个后链接功能。当编译器遍历您的DOM节点时,从父母到子节点:

  • 控制器在下行时首先实现
  • preLink功能在下来的路上执行
  • postLink函数在上升的过程中执行

Directive controller and link timing in AngularJS