调用service方法后,AngularJs更新指令

时间:2015-03-17 21:34:24

标签: javascript angularjs angularjs-directive

我正在尝试创建可重复使用的提醒服务,我只需在我的应用程序中的任何地方调用:

alertService.showAlert('warning', 'something went wrong!');

例如在ajax调用后端api之后。 现在我正在使用工厂和指令,但似乎我做错了,因为在调用showAlert方法后指令没有更新。现在我有这样的事情:

var srv = angular.module('srv', []);
srv. factory('alertService', ['$timeout', function($timeout){
    var alertService = this;
        alertService.alertNeeded = false;
        alertService.alertClass = '';
        alertService.alertMessage = '';
        alertService.setAlertNeeded = function(){
            alertService.alertNeeded = true
        };
        alertService.setAlertClass = function(type){
            if(type === 'warning')
                alertService.alertClass = 'alert-warning';
            if(type === 'success')
                alertService.alertClass = 'alert-success';
            if(type === 'info')
                alertService.alertClass = 'alert-info';
            if(type === 'danger')
                alertService.alertClass = 'alert-danger';
        };
        alertService.setAlertMessage = function(message){
            alertService.alertMessage = message;
        };

        return {
            showAlert: function(class, msg){
                alertService.setAlertNeeded();
                alertService.setAlertClass(class);
                alertService.setAlertMessage(msg);
            }
        };
 }]).
 directive('myAlerts', ['alertService', function(alertService){
        return {
            restrict: 'A',
            template: '<div ng-class="alertClass" ng-show="alertNeeded">{{alertMessage}}</div>',
            link: function(scope){                   
                    scope.alertNeeded = alertService.alertNeeded;
                    scope.alertMessage = alertService.alertMessage;
                    scope.alertClass = alertService.alertClass;
            }
        }
    }]).
 controller('alertShowingController', ['$scope', 'alertService', function($scope, alertService){
     alertService.showAlert('warning', 'Warning alert!!!')   
 }]);

我的代码看起来并不完全相同,但我只想展示我想要做的事情:我想从另一个模块中的另一个控制器调用alertService.showAlert(...)(这取决于 srv 模块)并以这种方式更新myAlerts指令中的变量以显示正确的警报。

事情是在调用showAlert方法之后设置了值,但在指令代码中我将alertService.alertNeeded作为undefined

我对AngularJs来说是全新的,所以也许我犯了错误,但我花了整整一个晚上才能使它工作,我仍然不知道对此有什么合适的解决方案。

请帮忙!

2 个答案:

答案 0 :(得分:2)

这是我之前使用过的模式

var srv = angular.module('srv', []);
srv.factory('alertService', ['$timeout', function($timeout){
    var alertListeners = [];

    this.register = function (listener) {
        alertListeners.push(listener);
    };

    this.notifyAll = function (data) {
        for (// each listener in array) {
            var listenerObject = alertListeners[i];
            try { // do not allow exceptions in individual listeners to corrupt other listener processing
                listenerObject.notify(data);
            } catch(e) {
                    console.log(e);
            }   
        }
    };
 }]).
 directive('myAlerts', ['alertService', function(alertService){

     var alertDirectiveObserver = function($scope, alertService) {

         this.notify = function(data) {
            /*
             * TO DO - use data to show alert
             */
         };

         alertService.register(this);
     };


   return {
     restrict: 'A',
     template: '<div ng-class="alertClass" ng-show="alertNeeded">{{alertMessage}}</div>',
     controller: ['$scope', 'alertService', alertDirectiveObserver],
     link: function(scope){  
     }
    }
}]).
controller('alertShowingController', ['$scope', 'alertService',   function($scope, alertService){
    alertService.notifyAll({'warning', 'Warning alert!!!'})   
 ]);

当然你也应该通过注册一个删除范围破坏对象的函数进行清理。

例如

element.on('$destroy', function() {
    alertService.unregister(// some listener id);
});

答案 1 :(得分:0)

您的代码对alertService有两种不同的含义。在工厂定义中,它指的是工厂本身。在其他地方,它指的是工厂返回的对象。向前推进的最简单方法是向工厂返回的对象添加一些缺少的方法:

return {
    showAlert: function(cssClass, msg){
        alertService.setAlertNeeded();
        alertService.setAlertClass(cssClass);
        alertService.setAlertMessage(msg);
    },

    alertClass: function() { return alertService.alertClass; },     
    alertMessage: function() { return alertService.alertMessage; },
    alertNeeded: function() { return alertService.alertNeeded; }
};

然后,更改指令的模板,以便在每个摘要周期调用这些函数:

directive('myAlerts', ['alertService', function(alertService){
        return {
            restrict: 'A',
            template: '<div ng-class="alertClass()"' +
                      '     ng-show="alertNeeded()">' +
                      '  {{alertMessage()}}' +
                      '</div>',
            link: function(scope){                   
                scope.alertNeeded = alertService.alertNeeded;
                scope.alertMessage = alertService.alertMessage;
                scope.alertClass = alertService.alertClass;
            }
        }
}])

然后你应该看到你的警告信息。 Try it in a fiddle