1

I didn't know a better way to phrase that question. I've written a basic service to be used by two controllers.

JsFiddle: http://jsfiddle.net/aditya/2Nd8u/2/

Clicking 'notify' works as expected; it adds a notification to the array. But 'reset' breaks it. Clicking either button after 'reset' doesn't do anything. Does anyone know what's going on here?

PS. I think it has something to do with Angular losing the reference since notifs is being re-assigned (technically), so I wrote getters and setters, but even emptying the array involves pop()ing till it's empty, which doesn't seem very efficient.

Plunkr if JsFiddle is down: http://plnkr.co/edit/mzfLLjFXCwsxM5KDebhc

aditya
  • 1,978
  • 3
  • 17
  • 22

2 Answers2

4

I've forked your plunker and propose a solution:

In reset function, try to remove the objects of the array instead of declaring as new empty array:

notificationService.notifs.splice(0, notificationService.notifs.length);

Or, like suggested by @Wizcover:

notificationService.notifs.length = 0

This will notify angular that are modifications in the original array.

Deividi Cavarzan
  • 10,034
  • 13
  • 66
  • 80
2

I changed your service to this:

.factory("notificationService", function(){
    var notifications = [];
    return {
        notifs: notifications,
        clear: function(){
            angular.copy([], notifications);
        },
        get: function(){ 
            return notifs; 
        }
    }
})

and your controller :

$scope.reset = function(){
        console.log("reset");
        notificationService.clear();
        console.log(notificationService);
    }

and it works for me.

Naturally it should be a little bit tidier, in that instead of notifs you should have a get, and add and a remove method, but i just wanted to show you where the code changed. The angular.copy is the method that makes sure the changes are made within angular's lifecycle.

As you can't bind variable but only methods, you could do this:

$scope.getNotifications = notificationService.get;

That should work.

Joe Minichino
  • 2,793
  • 20
  • 20
  • My question was why my code wasn't working. Is this the accepted practice when dealing with objects and Angular? To copy instead of re-assign? – aditya Aug 15 '13 at 18:51