AngularJS Scope在异步调用后不在视图中更新

前端之家收集整理的这篇文章主要介绍了AngularJS Scope在异步调用后不在视图中更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在向API发出请求时,我无法在前端更新我的示波器.在后端,我可以看到我的$scope变量的值正在改变,但这并没有在视图中反映出来.

这是我的控制器.

Controllers.controller('searchCtrl',function($scope,$http,$timeout) {
   $scope.$watch('search',function() {
      fetch();
   });

 $scope.search = "Sherlock Holmes";

 function fetch(){
   var query = "http://api.com/v2/search?q=" + $scope.search + "&key=[API KEY]&format=json";
    $timeout(function(){
      $http.get(query)
      .then(function(response){ 
        $scope.beers = response.data; 
        console.log($scope.beers);
      });
    });  
 }
});

这是我的HTML的片段

<div ng-if="!beers">
  Loading results...
</div>
<p>Beers: {{beers}}</p>
<div ng-if="beers.status==='success'">

  <div class='row'>
    <div class='col-xs-8 .col-lg-8' ng-repeat="beer in beers.data track by $index" ng-if="beer.style">
    <h2>{{beer.name}}</h2>          
    <p>{{beer.style.description}}</p>
    <hr>
    </div>
  </div>
</div>

<div ng-if="beers.status==='failure'">
  <p>No results found.</p>
</div>

我尝试了几种解决方案,包括使用$scope.$apply();但这只会造成常见错误

Error: $digest already in progress

以下帖子建议使用$timeout或$asyncDefault
AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

我上面的代码使用$timeout,我没有错误,但视图仍未更新.

帮助赞赏

我使用的是AngularJS 1.3,你可以在$scope.beers = response.data之后尝试$scope.$applyAsync();声明.

这是Angular文档中关于$applyAsync()的内容

Schedule the invocation of $apply to occur at a later time. The actual time difference varies across browsers,but is typically around ~10 milliseconds. 07000

更新

正如其他人所指出的,你不应该(通常)需要手动触发摘要周期.大多数时候,它只是指向您的应用程序的糟糕设计(或至少不是AngularJS友好设计).

目前在OP中,$watch会触发fetch方法.相反,如果该方法由ngChange触发,则应自动触发摘要周期.

以下是此类代码的示例:

HTML

// please note the "controller as" Syntax would be preferred,but that is out of the scope of this question/answer
<input ng-model="search" ng-change="fetchBeers()">

JavaScript的

function SearchController($scope,$http) {

    $scope.search = "Sherlock Holmes";

    $scope.fetchBeers = function () {
        const query = `http://api.com/v2/search?q=${$scope.search}&key=[API KEY]&format=json`;
        $http.get(query).then(response => $scope.beers = response.data);
    };

}
原文链接:https://www.f2er.com/angularjs/143378.html

猜你在找的Angularjs相关文章