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

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

这是我的控制器.

  1. Controllers.controller('searchCtrl',function($scope,$http,$timeout) {
  2. $scope.$watch('search',function() {
  3. fetch();
  4. });
  5.  
  6. $scope.search = "Sherlock Holmes";
  7.  
  8. function fetch(){
  9. var query = "http://api.com/v2/search?q=" + $scope.search + "&key=[API KEY]&format=json";
  10. $timeout(function(){
  11. $http.get(query)
  12. .then(function(response){
  13. $scope.beers = response.data;
  14. console.log($scope.beers);
  15. });
  16. });
  17. }
  18. });

这是我的HTML的片段

  1. <div ng-if="!beers">
  2. Loading results...
  3. </div>
  4. <p>Beers: {{beers}}</p>
  5. <div ng-if="beers.status==='success'">
  6.  
  7. <div class='row'>
  8. <div class='col-xs-8 .col-lg-8' ng-repeat="beer in beers.data track by $index" ng-if="beer.style">
  9. <h2>{{beer.name}}</h2>
  10. <p>{{beer.style.description}}</p>
  11. <hr>
  12. </div>
  13. </div>
  14. </div>
  15.  
  16. <div ng-if="beers.status==='failure'">
  17. <p>No results found.</p>
  18. </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

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

JavaScript的

  1. function SearchController($scope,$http) {
  2.  
  3. $scope.search = "Sherlock Holmes";
  4.  
  5. $scope.fetchBeers = function () {
  6. const query = `http://api.com/v2/search?q=${$scope.search}&key=[API KEY]&format=json`;
  7. $http.get(query).then(response => $scope.beers = response.data);
  8. };
  9.  
  10. }

猜你在找的Angularjs相关文章