【发布时间】:2016-06-06 13:28:15
【问题描述】:
我正在开发 angularjs 1.4。我试图让一些前端缓存集合在插入新数据时更新视图。我已经检查了这里 Angularjs watch service object 的其他答案,但我相信我没有覆盖数组,这意味着引用是相同的。
代码很简单:
(function(){
var appCtrl = function($scope, $timeout, SessionSvc){
$scope.sessions = {};
$scope.sessions.list = SessionSvc._cache;
// Simulate putting data asynchronously
setTimeout(function(){
console.log('something more triggered');
SessionSvc._cache.push({domain: "something more"});
}, 2000);
// Watch when service has been updated
$scope.$watch(function(){
console.log('Watching...');
return SessionSvc._cache;
}, function(){
console.log('Modified');
}, true);
};
var SessionSvc = function(){
this._cache = [{domain: 'something'}];
};
angular.module('AppModule', [])
.service('SessionSvc', SessionSvc)
.controller('appCtrl', appCtrl);
})();
我认为脏检查必须在不使用任何观察者的情况下捕获更改。我仍然让观察者检查触发 setTimeout 函数后是否执行了任何操作。我只是没有看到检测到更改。
这里是jsbin。我真的不理解某事或犯了一个非常糟糕的错误。
【问题讨论】:
-
$watchCollection在您的场景中是一个更好的选择。无论如何,您需要在异步回调中运行 $scope.$apply 以便 Angular 更新视图(有关详细信息,请参阅 stackoverflow.com/questions/15112584/…) -
使用 $timeout 服务。 SetTimeout 不会触发应用
-
@yeouuu 所说的 - 您在演示中注入了 $timeout 服务,但您正在调用 setTimeout。将 setTimeout 替换为 $timeout。
标签: angularjs