AngularJS:页面显示NaN并在从服务器获取数据时显示数据。怎么预防呢?

时间:2013-05-21 17:52:28

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

考虑这个控制器

  $scope.transaction = {};
  $scope.transactions = Transaction.query();

  $scope.save = function() {
    var transaction = new Transaction();
    transaction.name = $scope.transaction['name'];
    transaction.debit = $scope.transaction['debit'];
    transaction.date = $scope.transaction['date'];
    transaction.amount = $scope.transaction['amount'];
    transaction.category = $scope.transaction['category'].uuid;

    //noinspection JSUnresolvedFunction
    transaction.$save();
    $scope.transactions.push(transaction);
    console.log('transaction saved successfully', transaction);
  };

HTML

<tbody ng-repeat="transaction in transactions | orderBy: transaction.created_on">
      <td>{{ transaction.name }}</td>
      <td>{{ transaction.amount | currency }}</td>
      <!-- custom filter to display type of transaction -->
      <td>{{ transaction.debit | transactionType }}</td>
      <!-- added dateInMillis to pass to date to filter Angular way -->
      <td>{{ transaction.created_on | dateInMillis | date: 'medium'}}</td>
      <td>{{ transaction.category.name }}</td>
      <td>
</tbody>

问题
当我添加事务时,它立即显示一堆NaNs,然后一旦服务器返回保存的数据,它就会用实际数据替换那些NaNs

如何防止这种情况发生?它不是一个好UX

1 个答案:

答案 0 :(得分:3)

如果没有看到与Transaction对象相关的所有代码,很难确定问题是什么。一眼我认为你需要一个附加到transaction.$save()方法的回调函数。

transaction.$save(function(u, putResponseHeaders) {
    // This is $save's success callback
    $scope.transactions.push(transaction);
    console.log('transaction saved successfully', transaction);
});