Xakerok
Xakerok

Reputation: 233

Why is not updated scope in Angular JS?

I have the following code Angular JS:

appService.get({id : id}).then(function (response) {
   $scope.vm.events.push({title: 'New event', type: 'important', draggable: true,    resizable: true});
})

This code returns response from AJAX service and puts object to array $scope.vm.events.

So, in template I dont see this added element as: {{vm.events}}

There is also one function in the same controller:

$scope.add = function (){
   $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true});
}

When I call it I see new element in template: {{vm.events}}.

Why does not work code in the first case?

Upvotes: 0

Views: 351

Answers (2)

kilogic
kilogic

Reputation: 132

If you are not seeing it, it is because the promise is not being resolved.

Do try putting something in the rejection handling part of the promise (on a second function within the 'then()' block):

appService.get({id : id}).then(function (response) {
   $scope.vm.events.push({title: 'New event', type: 'important', draggable: true, resizable: true});
},
function(){
 $scope.vm.events.push({title: 'ERROR_EVENT', type: 'ERROR_CALLBACK', draggable: true, resizable: true});
});

Like others suggested, if this is outside of angular, please call for $scope.$apply() or $scope.$digest() to trigger a digest cycle so that your data can be updated.

By adding this second function you should be able to see if the promise was being resolved or not, and if the problem lies elsewhere.

Upvotes: 0

Tarun Dugar
Tarun Dugar

Reputation: 8971

This is because the callback function in your service is outside the angularjs digest cycle.

For tackling this, there are two ways:

Method 1:

The first way would be to use $scope.$apply just after your callback in the service has finished as follows:

appService.get({id : id}).then(function (response) {
   $scope.vm.events.push({title: 'New event', type: 'important', draggable: true,    resizable: true});
   $scope.$apply(); //this for updating your scope outside the digest cycle
})

Method 2:

Wrapping your service code inside a function inside the controller's scope as follows:

$scope.fn = function() {
    appService.get({id : id}).then(function (response) {
       $scope.vm.events.push({title: 'New event', type: 'important', draggable: true,    resizable: true});
    })
}

So, in this method, whenever you want to call the service just call this function. This is also the reason why your 'add' function updates the template because it is in the 'scope' of the controller and in the digest cycle.

Upvotes: 1

Related Questions