Update scope value when service data is changed

后端 未结 6 1245
天命终不由人
天命终不由人 2020-11-27 10:57

I have the following service in my app:

uaInProgressApp.factory(\'uaProgressService\', 
    function(uaApiInterface, $timeout, $rootScope){
        var facto         


        
6条回答
  •  旧巷少年郎
    2020-11-27 11:41

    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.

    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;
        }
    });
    

    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.

提交回复
热议问题