不在init()内触发事件

时间:2015-02-12 05:44:31

标签: javascript angularjs

我想触发一个事件,以便在屏幕上显示成功消息。通知事件在任何地方都正常工作,但是当我尝试在应用程序的init()函数中触发它时,虽然执行了该块中的其余代码,但它没有被执行。

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

            });
           appUtils.groupCreated = false;            }
    };

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

通知指令

.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) {
        $scope.$on("notifyEvent", function(e, notifyObject) {
           $scope.displayNotification = true;
            console.log("notification");
            // 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;
    }
}
});

0 个答案:

没有答案