我有以下服务于我的应用程序:
I have the following service in my app:
uaInProgressApp.factory('uaProgressService', function(uaApiInterface, $timeout, $rootScope){ var factory = {}; factory.taskResource = uaApiInterface.taskResource() factory.taskList = []; factory.cron = undefined; factory.updateTaskList = function() { factory.taskResource.query(function(data){ factory.taskList = data; $rootScope.$digest console.log(factory.taskList); }); factory.cron = $timeout(factory.updateTaskList, 5000); } factory.startCron = function () { factory.cron = $timeout(factory.updateTaskList, 5000); } factory.stopCron = function (){ $timeout.cancel(factory.cron); } return factory; });然后,我用它在控制器是这样的:
Then I use it in a controller like this:
uaInProgressApp.controller('ua.InProgressController', function ($scope, $rootScope, $routeParams, uaContext, uaProgressService) { uaContext.getSession().then(function(){ uaContext.appName.set('Testing house'); uaContext.subAppName.set('In progress'); uaProgressService.startCron(); $scope.taskList = uaProgressService.taskList; }); } );所以基本上我的服务更新 factory.taskList 每5秒和我联系这个 factory.taskList 到 $ scope.taskList 。然后,我尝试了不同的方法,如 $适用, $消化但 factory.taskList 不会反映在我的控制器和视图 $ scope.taskList 。
So basically my service update factory.taskList every 5 seconds and I linked this factory.taskList to $scope.taskList. I then tried different methods like $apply, $digest but changes on factory.taskList are not reflected in my controller and view $scope.taskList.
这仍然是我的模板是空的。你知道我怎么可以传播这些变化?
It remains empty in my template. Do you know how I can propagate these changes ?
推荐答案角(不像灰烬和一些其他的框架),不提供特殊的包裹的其中的对象半神奇留在同步。你操纵的对象是普通的JavaScript对象,只是好像说 VAR A = B; 没有的链接的变量 A 和 b ,称 $ scope.taskList = uaProgressService.taskList 没有链接这两个值。
Angular (unlike Ember and some other frameworks), does not provide special wrapped objects which semi-magically stay in sync. The objects you are manipulating are plain javascript objects and just like saying var a = b; does not link the variables a and b, saying $scope.taskList = uaProgressService.taskList does not link those two values.
对于这种链接 -ing,角提供的 $观看在 $范围 。你可以看的值 uaProgressService.taskList 和更新 $范围的值时,它改变:
For this kind of link-ing, angular provides $watch on $scope. You can watch the value of the uaProgressService.taskList and update the value on $scope when it changes:
$scope.$watch(function () { return uaProgressService.taskList }, function (newVal, oldVal) { if (typeof newVal !== 'undefined') { $scope.taskList = uaProgressService.taskList; } });传递给 $观看函数的第一个前pression会在每次的 $摘要循环,第二个参数是被调用,新与旧价值的功能。
The first expression passed to the $watch function is executed on every $digest loop and the second argument is the function which is invoked with the new and the old value.
更多推荐
当业务数据发生变化更新的范围值
发布评论