Aleks
Aleks

Reputation: 5340

Scope not updating in the view after promise is resolved

Even though there is a similar question for this Data is not getting updated in the view after promise is resolved but I am already using this approach and the view is not being updated.

I have a factory:

'use strict';

myApp
.factory('Factory1', [ '$http','$q','$location', '$rootScope', 'Service', function($http, $q, $location, $rootScope, Service){

    return {

        checkSomething: function(data){

          var deferred = $q.defer();  //init promise

          Service.checkSomething(data,function(response){
                // This is a response from a get request from a service
                deferred.resolve(response);
          });

          return deferred.promise;
        }
    };
}]);

I have a controller:

'use strict';

myApp
.controller('MyCtrl', ['$rootScope', '$scope', '$location','Service', 'Factory1' function($rootScope, $scope, $location, Service, Factory1) {


    if(Service.someCheck() !== undefined)
    {
      // Setting the variable when view is loaded for the first time, but this shouldn't effect anything
      $scope.stringToDisplay = "Loaded";

    }


    $scope.clickMe = function(){
      Factory1.chechSomething($scope.inputData).then(function(response){
          $scope.stringToDisplay = response.someData; // The data here is actually being loaded!

      });
    };

}]);

And the view:

<div class="app " ng-controller="MyCtrl">    
    {{stringToDisplay}}    
    <button class="button" ng-click="clickMe()">Update display</button>    
</div>

But the data is not being updated in the view when I click on a button "Update display". Why?

Even though the $scope is being loaded with the data

EDIT:

Hm, it seems that I am getting a error when I try $scope.$apply() and it says:

[$rootScope:inprog] $digest already in progress

Upvotes: 14

Views: 17682

Answers (2)

Michael Jess
Michael Jess

Reputation: 1907

This might be a digest cycle issue. You could try:

...
$scope.stringToDisplay = response.someData;
$scope.$apply();
...

For the sake of completeness, here is a nice wrap-up of $scope.$apply.

Edit: I tried to reproduce the error in this fiddle, but cannot seem to find any issues. It works flawlessly without $scope.$apply. I use setTimeout in order to simulate asynchronous operations, which should not trigger a digest cycle by itself.

Upvotes: 15

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Try this instead of your function

$scope.clickMe =$scope.$apply(function(){
      Factory1.chechSomething($scope.inputData).then(function(response){
          $scope.stringToDisplay = response.someData; // The data here is actually being loaded!

      });
    });

Upvotes: 0

Related Questions