【问题标题】:ng-repeat not working when binded data defined in XMLHttpRequest当 XMLHttpRequest 中定义的绑定数据时,ng-repeat 不起作用
【发布时间】:2017-03-24 16:26:41
【问题描述】:

我目前有以下html代码...

<li ng-repeat="a in idmasVesselstableList"><a>{{a.table_name}}</a></li>

还有下面的 AngularJS 控制器代码...

angular
  .module('myApp')
  .controller('idmasCtrl', ['$scope', function($scope) {

      $scope.idmasVesselstableList = [{"table_name":"api_574_structural_thickness"},{"table_name":"api_574_structural_thickness_rev_history"},{"table_name":"cml"},{"table_name":"cml_rev_history"},{"table_name":"cml_types"},{"table_name":"cml_types_rev_history"},{"table_name":"damage_mechanism"},{"table_name":"damage_mechanism_list"},{"table_name":"damage_mechanism_list_rev_history"},{"table_name":"damage_mechanism_rev_history"},{"table_name":"equipment"},{"table_name":"equipment_rev_history"},{"table_name":"inspection"},{"table_name":"inspection_rev_history"},{"table_name":"inspection_statuses"},{"table_name":"inspection_statuses_rev_history"},{"table_name":"remediation_statuses"},{"table_name":"remediation_statuses_rev_history"},{"table_name":"statuses"},{"table_name":"statuses_rev_history"}];

  }])

哪个工作正常并且可以正确加载我的列表。

但是,当我在 XMLHttpRequest 中定义我的列表时,AngularJS 无法正确生成此列表。请参阅下面的代码...

angular
  .module('myApp')
  .controller('idmasCtrl', ['$scope', function($scope) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET","/getvesselstablelist.js", true);
      xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
           string=xmlhttp.responseText;
           $scope.idmasVesselstableList = JSON.parse(string);
         }
       }
  xmlhttp.send();
}])

有谁知道我如何在 readystatechange 的 XXMLHttpRequest 中正确生成列表?

提前感谢您的帮助。

【问题讨论】:

  • 尝试在 API 调用之前定义一个空数组,在控制器函数的开头,例如 $scope.idmasVesselstableList = [];
  • @ex0dm3nt 我试过了,但没有任何区别,不过感谢您的建议

标签: javascript angularjs xmlhttprequest angularjs-ng-repeat


【解决方案1】:

首先为 AJAX 使用 Angular $http 服务。 所以它会是:

$http.get("/getvesselstablelist.js").then(function(response){
   $scope.idmasVesselstableList = JSON.parse(response.data);
});

如果由于某种原因您不能使用它,请在您的 XMLHttpRequest 回调中调用 $scope.$apply。 您需要这个来告诉 Angular 范围已更新,在 Angular 代码之外。

xmlhttp.onreadystatechange=function(){
   if (xmlhttp.readyState==4 && xmlhttp.status==200){
     string=xmlhttp.responseText;
     $scope.$apply(function(){
       $scope.idmasVesselstableList = JSON.parse(string);
     });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    相关资源
    最近更新 更多