简体   繁体   中英

Value in view not updating after $promise is resolved

I have a value in my view that is not updating after a service method is called.

Here is the relevant code in the controller:

$scope.remaining = 20;

AcctService.getCurrentCount.get(calculateRemaining); //This is a $resource method

function calculateRemaining(result) {
    $scope.remaining -= result;
    alert($scope.remaining);
}

Here is the code for .getCurrentCount :

service.getCurrentCount = $resource('/api/getCount', {}, {
        'get': { method: 'GET', isArray: true }
    });

With the above code, say for example the result returned is 5. "15" will be alerted. However, in the view, {{remaining}} is still 20. No errors, the view just doesn't update.

I have tried the following:

  • $timeout - nothing different happens
  • Making $scope.remaining an object with property "value". (I read in another post about issues with data binding of primitives vs references). No difference.
  • $promise and .then() - no difference
  • $apply results in a digest error

Note, I am also coding with Ionic, not sure if it makes a difference. I disabled caching in the Ionic config, and another service method that returns an array propagates an ng-repeat as expected.

Thanks!

I'm not sure what things look like inside that get() function, but it doesn't look right. Assuming get() returns a promise, you should write it like this:

AcctService.getCurrentCount.get().then(calculateRemaining); //This is a $resource method

First of all you do not need to create get method to return array. Use default 'query' method of $resource. And first parameter for the method is an object of parameters. second one is success function. So change you service to this

service.getCurrentCount = $resource('/api/getCount');

And later use it as

AcctService.getCurrentCount.query({},calculateRemaining); 

Also check if you are not using one way data binding {{::remaining}}

And also you have to make sure you are using right $scope, to check that make "remaining" a field of an object. You can do it this way:

$scope.myData = {};
$scope.myData.remaining = 20;

and later at the controller initialize it the same and at the html

{{myData.remaining}}

also you can use $scope.apply(); but actually that is used at different case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM