AngularJS ng-switch在加载之前

时间:2014-05-09 01:25:39

标签: javascript angularjs ngresource

我有一个AngularJS模板,如下所示:

<table data-ng-switch data-on="data.length">
    <tbody data-ng-switch-when="0">
        <tr>
            <td>No data available.</td>
        </tr>
    </tbody>
    <tbody data-ng-switch-default>
        <tr data-ng-repeat="row in data">
            <td>{{row.name}}</td>
        </tr>
    </tbody>
</table>

我的控制器和工厂看起来像这样:

demo.factory('Demo', function($resource) {
    return $resource('data.json');
});

demo.controller('DemoController', ['$scope', '$state', '$stateParams', 'Demo', function($scope, $state, $stateParams, Demo) {   
    $scope.data = Demo.query();
}]);

有没有办法阻止“无数据可用”。在从资源中检索数据之前快速在屏幕上闪烁?

2 个答案:

答案 0 :(得分:0)

在父元素上使用ng-cloak。

<div ng-cloak>
    :: all the bindings that you want to wait for the bind to hapen
</div>

AngularJS ng-cloak

答案 1 :(得分:0)

发生这种情况的原因是$ resource服务返回一个空对象,该对象在获取请求的数据后异步填充。

解决这个问题:

  1. 从非$ scope变量分配请求的数据。
  2. query()操作中创建一个函数回调。
  3. 步骤2 中创建的函数回调中为$ scope.data中的非$scope变量分配。
  4. e.g。

    demo.controller('DemoController', ['$scope', '$state', '$stateParams', 'Demo', function($scope, $state, $stateParams, Demo) {   
        var queryData = Demo.query(function() {
          $scope.data = queryData;
        })
    }]);
    

    您可能会看到其他examples in here