AngularJS:如何在渲染之前从服务器填充数据?

时间:2013-04-24 23:02:21

标签: javascript angularjs

我的HTML

<div id="categories" ng-controller="AddTransactionCtrl">
    <tr ng-repeat="category in categories">
        <td><a href="{{category.name}}" target="_blank">{{category.name}}</a></td>
        <td>{{category.description}}</td>
    </tr>
</div>

我想从Controller中填充此列表,从服务器获取数据。我的控制器看起来像

function AddTransactionCtrl($scope, $http) {
  $scope.transaction = {};
  $scope.transaction.categories = [];
  $http({
    method: 'GET',
    url: '/categories'
  }).success(function(data, status, headers, config) {
      console.log('/categories succeeded. - ' + data.length);
      $scope.transaction.categories = data;
    }).error(function(data, status, headers, config) {
      console.log('/categories failed.');
    });

  console.log($scope.transaction.categories.length);

  $scope.save = function() {
    console.log('will add transaction');
    console.log('name:' + $scope.transaction.name);
    console.log('date:' + $scope.transaction.date);
    console.log('desc:' + $scope.transaction.desc);
  }
}

当我刷新页面并在Chrome控制台上看到时,我看到了

0
/categories succeeded. - 151
  • 表示未分配$scope.transaction.categories
  • 同样在我看到日志0打印在http日志之前,这意味着调用是异步的,并解释了为什么长度为0

问题
a。)在打印出与页面或控制台上的渲染相关的任何内容之前,如何确保通过HTTP填充类别

1 个答案:

答案 0 :(得分:3)

你说这是非同步的。在填充categories后需要执行的操作应该在success调用的$http回调函数内。

此外,您的ng-repeat指令错误。它应该是

<tr ng-repeat="category in transaction.categories">

使用这样的代码设置,tr元素现在只会在transaction.categories调用填充$http后显示。

另外,你说

  

这意味着未分配$ scope.transaction.categories

这不正确。它尚未被分配尚未。您的最终$http电话应如下所示:

function AddTransactionCtrl($scope, $http) {
  $scope.transaction = {};
  $scope.transaction.categories = [];
  $http({
    method: 'GET',
    url: '/categories'
  }).success(function(data, status, headers, config) {
      console.log('/categories succeeded. - ' + data.length);
      $scope.transaction.categories = data;

      // this will show you the count that you expect
      console.log($scope.transaction.categories.length);
    }).error(function(data, status, headers, config) {
      console.log('/categories failed.');
    });

  // this will always print 0 to console
  // since categories has not been assigned yet
  console.log($scope.transaction.categories.length);

  // other methods
}