Question

I'm trying to create a simple messaging service (see jsFiddle) using AngularJS and it's working for the most part. However, my "clearAlerts()" method doesn't seem to have any effect. I'm new to Angular, so I'm not sure what I'm doing wrong?

Here's the jsFiddle http://jsfiddle.net/uberspeck/j46Yh/

...and the code

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??
        }
    };
});​
Was it helpful?

Solution 2

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

OTHER TIPS

An alternate solution is to just remove the properties on the alerts.

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

    clearAlerts: function() {
        for(var x in this.alerts) {
           delete this.alerts[x];
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top