angularjs:using xmlhttprequest 将数据添加到 $scope 而不是 $http,但它不起作用

angularjs:using xmlhttprequest to add data to $scope rather than $http, but it unworks

我正在学习'XHRs & Dependency Injection'angularjs的官方教程。

它引入了 $http 服务来从同一域下的一些文件中获取 json。

我想尝试原始的 XMLHttpRequest 来获取 json。

我得到了数据,但视图上没有任何显示,使用 $http 时应该有电话列表。

演示代码:

  $http.get('phones/phones.json').success(function(data) {
     $scope.phones = data;
  });

我写来替换的内容:

var xmlhttp=null;
  if(window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if(xmlhttp!=null)
  {
    xmlhttp.onreadystatechange=state_Change;
    xmlhttp.open("GET", 'phones/phones.json', true);
    xmlhttp.send(null);
  }
  else{
    alert("Your browser does not support XMLHTTP.");
  }

  function state_Change()
  {
    if(xmlhttp.readyState==4)
    {// 4 = "loaded"
      if(xmlhttp.status==200)
      {// 200 = OK
        var phoneList=JSON.parse(xmlhttp.responseText);

        $scope.phones=phoneList;
        console.log($scope); // ChildScope {$$childTail: null, $$childHead: null, $$nextSibling: null, $$watchers: Array[3], $$listeners: Object…}

        console.log($scope.phones); // object, actually what is.But it can't be reflected to the view.There is nothing where should be a list.
              }
              else{
                alert("Problem retrieving XML data");
              }
            }
          }

您的分配是在 onreadystatechange 事件处理程序中执行的。并且该事件在 angular 消化周期之外触发。在这种情况下,您必须告诉 angular 检测更改。您将使用 $scope:

$applyAsync 方法执行此操作
...
var phoneList=JSON.parse(xmlhttp.responseText);
$scope.$applyAsync(function(){
   $scope.phones=phoneList;
})
...

但通常您应该按照建议使用 $http。它为你解决消化问题。