Search code examples
javascriptangularjsxmlhttprequestangularjs-ng-repeat

ng-repeat not working when binded data defined in XMLHttpRequest


I currently have the following html code...

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

And the following AngularJS controller code...

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"}];

  }])

Which works fine and correctly loads my list.

However, when I define my list within a XMLHttpRequest this list is not generated correctly by AngularJS. See code below...

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

Anyone know how I can get the list to generate correctly inside the XXMLHttpRequest on readystatechange?

Thanks in advance for any help.


Solution

  • First of all use Angular $http service for AJAX. So it will be :

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

    And if for some reason you cant use it, call $scope.$apply in your XMLHttpRequest callback. You need this to tell angular that scope was updated, outside of an angular code.

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