我有一个相当大的应用程序,我正在建设,并希望确保我得到这个权利。
第一个表如预期为空。
但是当http调用完成时,watch不会再次被触发。
但是从http调用的品牌是在作用域中,因为使用ng-repeat工作
我宁愿不使用$broadcast,因为我觉得它会使我的一些使用$watch的指令变得复杂。
这里有一个活塞:http://plnkr.co/edit/L1SNV7mt6x7XCF4QFDPk?p=preview
var app = angular.module('app', []);
app.controller('main', function($scope, $http, Brand) {
$scope.brands = Brand.all;
$scope.$watch('brands', function(old, neww) {
console.log('brands', old, neww);
});
});
app.factory('Brand', function($http) {
var brands = {
all: [],
add: function(item) {
brands.all.push(item);
},
get: function() {
brands.all = [];
$http.get('json.txt').success(function(data) {
_.each(data, function(brand){
brands.add(Model(brand));
});
});
}
};
var Model = function(item) {
return item;
};
brands.get();
return brands;
});
尝试将$watch
中的3d参数设置为true
:
$scope.$watch('brands', function(old, neww) {
console.log('brands', old, neww);
}, true);
它会说angular来观察更深。文档
这与AngularJS如何检测它所监视的项的变化有关。对于简单地观察元素是否从数组中添加或删除,您将需要使用$watchCollection
而不是$watch
。
更新砰砰作响。