在解除承诺后,视图中的范围不会更新

Ale*_*eks 12 angularjs

即使有一个类似的问题,这个数据在承诺解决后未在视图中得到更新,但我已经在使用这种方法并且视图没有被更新.

我有一家工厂:

'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;
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

我有一个控制器:

'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!

      });
    };

}]);
Run Code Online (Sandbox Code Playgroud)

并且观点:

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

但是当我点击"更新显示"按钮时,视图中的数据没有更新.为什么?

即使$scope正在加载数据

编辑:

嗯,我尝试时似乎遇到错误$scope.$apply(),它说:

[$rootScope:inprog] $digest already in progress
Run Code Online (Sandbox Code Playgroud)

Mic*_*ess 12

这可能是一个摘要周期问题.你可以尝试:

...
$scope.stringToDisplay = response.someData;
$scope.$apply();
...
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这里有一个很好的总结$scope.$apply.

编辑:我试图重现这个小提琴中的错误,但似乎无法找到任何问题.它完美无缺$scope.$apply.我用setTimeout它来模拟异步操作,它本身不应该触发摘要循环.

  • hm x 2当我尝试申请时,它表示"$ digest已在进行中" (3认同)