2

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>

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

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 填充

4

1 回答 1

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
}
于 2013-04-24T23:34:28.793 回答