【问题标题】:angularjs:using xmlhttprequest to add data to $scope rather than $http, but it unworksangularjs:使用 xmlhttprequest 将数据添加到 $scope 而不是 $http,但它不起作用
【发布时间】:2015-08-09 11:57:40
【问题描述】:

我正在通过angularjs的官方教程学习“XHRs & Dependency Injection”。

它引入了$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");
              }
            }
          }

【问题讨论】:

  • 你没有明白这一点。

标签: angularjs http callback scope xmlhttprequest


【解决方案1】:

您的分配在onreadystatechange 事件处理程序中执行。并且该事件是在角消化周期之外触发的。在这种情况下,您必须告诉 angular 来检测变化。你可以使用$scope$applyAsync 方法来做到这一点:

...
var phoneList=JSON.parse(xmlhttp.responseText);
$scope.$applyAsync(function(){
   $scope.phones=phoneList;
})
...

但通常您应该按照 entre 的建议使用 $http。它为您处理消化问题。

【讨论】:

  • 非常感谢。我查看了开发人员指南,发现 $scope.$apply 也可以做到这一点。 $apply 和 $applyAsync 之间的区别在于后者在以后发生。
  • 使用$apply,如果你从现有的角度摘要循环中调用你的函数,你总是冒着得到already in digest cycle 错误的风险。您的 state_Change 函数不知道调用它的上下文。但是,如果您 100% 确定此函数将仅用作 xmlhttprequest 事件处理程序,则可以使用 $apply
  • 它回答了你的问题吗?
猜你喜欢
  • 2011-09-08
  • 2016-09-21
  • 2019-07-28
  • 1970-01-01
  • 2014-05-14
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多