Reputation: 1505
I'm using angularJS and I do this:
xxx.then(function (response) {
$scope.x = response.x;
$scope.y = response.y;
}, function (error) {}
);
The response come from server not instantantly. Then when the response come, I want than the scope update my value, but it does that just when I click in some button other so.
In my html I receive the informations so:
<p>{{x}}</p>
<p>{{y}}</p>
Do you know what I'm doing wrong?
Upvotes: 0
Views: 73
Reputation: 48968
A .then
method may fail to update the DOM if the promise comes from a source other than the $q service. Use $q.when
to convert the external promise to a $q service promise:
//xxx.then(function (response) {
$q.when(xxx).then(function (data) {
$scope.x = data.x;
$scope.y = data.y;
}, function (error) {
throw error;
});
The $q service is integrated with the AngularJS framework and the $q service .then
method will automatically invoke the framework digest cycle to update the DOM.
$q.when
Wraps an object that might be a value or a (3rd party) then-able promise into a
$q
promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
-- AngularJS $q Service API Reference - $q.when
Upvotes: 0
Reputation: 3266
This could be an issue with the digest cycle, try doing $scope.$apply()
like below :
xxx.then(function (response) {
$scope.x = response.x;
$scope.y = response.y;
$scope.$apply();
}, function (error) {});
In AngularJS the results of promise resolution are propagated asynchronously, inside a $digest cycle. So, callbacks registered with then() will only be called upon entering a $digest cycle.
The results of your promise will not be propagated until the next digest cycle. As there is nothing else in your code that triggers the digest cycle, changes are not getting applied immediately. But, when you click on a button , it triggers the digest cycle, due to which the changes are getting applied
Check this for a clear explanation about this.
Upvotes: 1