【问题标题】:Scope not updating in the view after promise is resolved承诺解决后,范围未在视图中更新
【发布时间】:2014-03-28 23:41:59
【问题描述】:

尽管这个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', '$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!

      });
    };

}]);

还有观点:

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

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

即使$scope 正在加载数据

编辑:

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

[$rootScope:inprog] $digest already in progress

【问题讨论】:

    标签: angularjs


    【解决方案1】:

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

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

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

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

    【讨论】:

    • hmm,添加$scope.$apply(); 无效:/,我将尝试另一种方法
    • hm x 2 当我尝试应用时它显示$digest already in progress
    • 我明白了。有趣的是,我无法重现该问题in this fiddle
    • 有趣。也许问题是我在其他地方使用apply,当我在这里尝试做同样的事情时它在抱怨。小提琴很有趣,也很有帮助。我会调查一下,稍后再回复你。 + 好听的小提琴
    • 不客气。事实上,我很惊讶使用setTimeout 不需要我们调用$apply
    【解决方案2】:

    试试这个而不是你的函数

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

    【讨论】:

    • 如果我添加$scope.$apply,我什至无法单击按钮:) 但我尝试了function(){$scope.$apply( //inside code)},但它仍然不起作用:/
    • Aleks,我也遇到了同样的问题,你解决了吗?
    猜你喜欢
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 2017-03-02
    • 2019-02-10
    • 2020-03-16
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多