1

我正在尝试使用 AngularJS 创建一个简单的消息传递服务(请参阅 jsFiddle),并且它大部分都在工作。但是,我的“clearAlerts()”方法似乎没有任何效果。我是 Angular 的新手,所以我不确定我做错了什么?

这是 jsFiddle http://jsfiddle.net/uberspeck/j46Yh/

...和代码

var App = angular.module('App', []);

function AlertsCtrl($scope, alertsManager) {
    $scope.alerts = alertsManager.alerts;
}

function FooCtrl($scope, alertsManager) {
    $scope.doGood = function() {
        alertsManager.addAlert('Yay!', 'alert-success');
    };
    $scope.doEvil = function() {
        alertsManager.addAlert('Noooo!', 'alert-error');
    };
    $scope.reset = function() {
        alertsManager.clearAlerts();
    };
}

App.factory('alertsManager', function() {
    return {
        alerts: {},
        addAlert: function(message, type) {
            this.alerts[type] = this.alerts[type] || [];
            this.alerts[type].push(message);
        },
        clearAlerts: function() {
            this.alerts = {}; // <= not working??
        }
    };
});​
4

2 回答 2

0

另一种解决方案是仅删除警报上的属性。

http://jsfiddle.net/j46Yh/4/

    clearAlerts: function() {
        for(var x in this.alerts) {
           delete this.alerts[x];
        }
    }
于 2012-10-25T19:15:20.723 回答
0

Pawel Kozlowski was kind of enough to provide my answer via the AngularJS mailing list. I simply had to change one line in my AlertsCtrl...

function AlertsCtrl($scope, alertsManager) {
    $scope.alertsManager = alertsManager;
}

Check out the new working jsFiddle

于 2012-10-20T16:33:52.977 回答