Taron Mehrabyan
Taron Mehrabyan

Reputation: 2229

problems with $watch function

I'm not really sure about this issue but it seems that sometimes when I activate $watch for a function then it doesn't work. for example I have this simple service

angular.module('sp-app').factory('mediaSources', function() {
    var storages = [];
    return {
        addStorage: function(storage) {
            storages.push(storage);

        },
        getStorages: function() {
            return storages;
        }

    }

});

and when I watch getStorage method in order to update my view it doesn't call change callback or calls only at initialization stage

$scope.$watch(function($scope) {            
        return mediaSources.getStorages();
    }, function() {     
        console.log('call')
    });

and I can only track changes by watching length property of returned array

return mediaSources.getStorages().length; and I wonder because I have written similar think somewhere else within my application and it works fine.

Upvotes: 1

Views: 104

Answers (2)

dfsq
dfsq

Reputation: 193311

You will have to set up watcher with equality flag as the third argument:

$scope.$watch(function($scope) {
    return mediaSources.getStorages();
}, function() {
    console.log('call');
}, true);

Upvotes: 0

ajmajmajma
ajmajmajma

Reputation: 14216

If i interpret what you are trying to do, you should not need to set a watch on something like this, you can just use a factory like so :

angular.module('app').factory('mediaSources', function(){
     var storages = {};

     storages.list = [];

     storages.add = function(message){
         storages.list.push(message);
     };

     return storages;
});

then in the controller you want to receive/update the data to for instance, you would do

 $scope.myControllerVar = mediaSources.list;

No need to watch over it, it should update for you.

Upvotes: 1

Related Questions