$ watch功能的问题

时间:2015-11-02 19:48:01

标签: angularjs angularjs-scope

我对这个问题不太确定,但似乎有时当我激活$ watch for a function时它就不起作用了。 例如,我有这个简单的服务

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

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

    }

});

当我观看getStorage方法以更新我的视图时,它不会在初始化阶段调用更改回调或调用

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

我只能通过观察返回数组的长度属性来跟踪更改

return mediaSources.getStorages().length; 我想知道,因为我在我的应用程序中的其他地方写过类似的想法并且它工作正常。

2 个答案:

答案 0 :(得分:1)

如果我解释你想要做什么,你不需要设置这样的东西,你可以使用这样的工厂:

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

     storages.list = [];

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

     return storages;
});

然后在控制器中你想要接收/更新数据,例如,你会做

 $scope.myControllerVar = mediaSources.list;

无需关注它,它应该为您更新。

答案 1 :(得分:0)

您必须将equality flag作为第三个参数设置为观察者:

dtype=object
相关问题