angularjs – 承诺解决后,范围不会在视图中更新

前端之家收集整理的这篇文章主要介绍了angularjs – 承诺解决后,范围不会在视图中更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
即使这个 Data is not getting updated in the view after promise is resolved有一个类似的问题,但是我已经在使用这种方法,而且没有更新视图.

我有一个工厂:

'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;
        }
    };
}]);

我有一个控制器:

'use strict';

myApp
.controller('MyCtrl',['$rootScope','$scope','Factory1' function($rootScope,$scope,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!

      });
    };

}]);

和视图:

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

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

即使$范围正在加载数据

编辑:

嗯,看来我在尝试$scope时收到一个错误$apply(),它说:

[$rootScope:inprog] $digest already in progress
这可能是一个摘要循环问题.你可以试试:
...
$scope.stringToDisplay = response.someData;
$scope.$apply();
...

为了完整起见,here是一个很好的总结$scope.$apply.

编辑:我试图在this fiddle重现错误,但似乎找不到任何问题.它没有$范围,无瑕疵工作.我使用setTimeout来模拟异步操作,它不应该自动触发摘要循环.

猜你在找的Angularjs相关文章