我正在尝试使用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??
}
};
});
答案 0 :(得分:0)
Pawel Kozlowski足以通过AngularJS mailing list提供我的答案。我只需要在AlertsCtrl中更改一行......
function AlertsCtrl($scope, alertsManager) {
$scope.alertsManager = alertsManager;
}
答案 1 :(得分:0)
另一种解决方案是只删除警报上的属性。
clearAlerts: function() {
for(var x in this.alerts) {
delete this.alerts[x];
}
}