AngularJS:显示加载HTML,直到数据加载

问题描述:

我如何有AngularJS显示加载微调,直到数据加载完成?

How do I have AngularJS show a loading spinner until the data has finished loading?

如果我的控制器具有 $ scope.items = [{名:一}] 设置静态,和AJAX装载机其中填充 $ scope.items [0] ['lateLoader'] =你好,我想微调显示,直到AJAX加载完成,然后检索到的数据填充绑定范围。

If my controller has $scope.items = [{name: "One"}] set up statically, and an AJAX loader which populates $scope.items[0]['lateLoader'] = "Hello", I'd like the spinner to show until the AJAX load is complete, and then populate the bound span with the retrieved data.

<ul ng-repeat="item in items">
  <li>
    <p>Always present: {{item.name}}</p>
    <p>Loads later: <span ng-bind="item.lateLoader"><i class="icon icon-refresh icon-spin"></i></span></p>
  </li>
</ul>

这code立即填充绑定的跨度,并作为 item.lateLoader 为空微调被替换为空。

This code populates the bound span immediately, and as item.lateLoader is empty the spinner is replaced with nothing.

我应该怎样做干净?

我想创建一个自定义的指令,按照对方的回答,但这里是你如何能做到这一点没有它可能会得到之前学习的好主意指令为更复杂的功能..一对夫妇的注意事项:

I would create a custom directive as per the other answer, but here is how you could do it without the directive which might be a good idea to learn before getting into more complex functionality.. A couple things to note:


  1. 使用的setTimeout来模拟一个Ajax调用

  2. 加载图标preloaded并正在当隐藏在数据负载。只是一个简单的NG-hide指令。

  3. 有在我的例子只是一些文字,获取隐藏没有加载图像(很明显你的HTML将有正确的CSS参考资料)。

演示:http://plnkr.co/edit/4XZJqnIpie0ucMNN6egy?p=$p$pview

查看:

<ul >
  <li ng-repeat="item in items">
    <p>Always present: {{item.name}}</p>
    <p>Loads later: {{item.lateLoader}} <i ng-hide="item.lateLoader"  class="icon icon-refresh icon-spin">loading image i don't have</i></p>
  </li>
</ul>

控制器:

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.items = [{name: "One"}];
  setTimeout(function() {
    $scope.$apply(function() {
     $scope.items[0].lateLoader = 'i just loaded';  
    });
  }, 1000);
});