angularjs - promise 解决后,范围未在 View 中更新

标签 angularjs

尽管有一个类似的问题Data is not getting updated in the view after promise is resolved但我已经在使用这种方法,并且 View 没有更新。

我有一家工厂:

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

我有一个 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!

      });
    };

}]);

以及 View :

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

但是当我单击“更新显示”按钮时, View 中的数据并未更新。为什么?

即使 $scope 正在加载数据

编辑:

嗯,当我尝试 $scope.$apply() 时似乎出现错误,它显示:

[$rootScope:inprog] $digest already in progress

最佳答案

这可能是摘要循环问题。您可以尝试:

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

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

编辑:我尝试重现 this fiddle 中的错误,但似乎找不到任何问题。它可以在没有 $scope.$apply 的情况下完美运行。我使用 setTimeout 来模拟异步操作,该操作本身不应触发摘要周期。

关于angularjs - promise 解决后,范围未在 View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22036414/

相关文章:

angularjs - 如何使用 Angular-Strap 创建带有 Controller 的模态?

javascript - AngularJs 应用程序转到 div 的顶部

javascript - 将登录页面从 angularjs 重定向到欢迎页面

angularjs - 在 Angular 应用程序中缓存 parse.com Promise 的结果

angularjs - 如何在 mvc5 中使用 angular-google-maps 绘制多边形

angularjs - Angular : change data on ng-repeat with filter function

javascript - 如何在 Angular.js 中创建新的标签元素

javascript - 异步 XMLHttpRequest 响应后,ng-grid 未与最新数据绑定(bind)

javascript - 具有可以未定义的参数的 Angular getter/setter

javascript - 无法设置仅数字输入