2

我有一个视图事务,它有两个部分

a.) 查看交易
b.) 添加交易

两者都绑定到以下控制器

function TransactionController($scope, Category, Transaction) {
  $scope.categories = Category.query(function() {
    console.log('all categories - ', $scope.categories.length);
  });

  $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);

  }
}

,其中 Transaction 是一项服务,如下所示

angular.module('transactionServices', ['ngResource']).factory('Transaction', function($resource) {
    return $resource('/users/:userId/transactions/:transactionId', {
      // todo: default user for now, change it
      userId: 'bd675d42-aa9b-11e2-9d27-b88d1205c810',
      transactionId: '@uuid'
    });
  });

当我单击“事务”选项卡时,路由 #/transactions 被激活,导致它呈现子视图 a.) 和 b.)

我的问题是,
- 有没有办法在我添加新交易时更新 $scope.transactions?因为它是一种资源
,否则我将不得不手动执行 $scope.transactions.push(transaction);

4

2 回答 2

3

我的第一个答案,所以请放轻松...

您可以扩展 Transaction 资源来为您更新 $scope.transactions。它会是这样的:

angular.module( ..., function($resource) {
    var custom_resource = $resource('/users/:userId/transactions/:transactionId', {
        ...
    });

    custom_resource.prototype.save_and_update = function (transactions) {
        var self = this;
        this.$save(function () {
            transactions.push(self);
        });
    };

    return custom_resource;
});

在您的控制器中,您将执行以下操作:

function TransactionController (...) {
    ...
    $scope.save = function () {
        ...
        // In place of: transaction.$save(), do:
        transaction.save_and_update($scope.transactions);
        ...
    }

}

注意:您需要确保您创建的对象在 $scope 中完全可用。我花了 30 分钟试图弄清楚为什么这个方法在我的代码上失败了,结果我在数据库中生成了身份代码。结果,我对添加新对象的所有后续操作都失败了,因为新对象缺少标识!!!

于 2013-05-08T09:00:32.890 回答
2

无法自动更新范围内的一组模型。您可以将其推送到 $scope.transactions,或者您可以调用一个方法来使用来自服务器的新数据更新 $scope.transactions。在任何情况下,您都应该在资源保存函数的成功回调中更新 $scope,如下所示:

transaction.$save({}, function() {
    $scope.transactions.push(transaction);
    //or
    $scope.transactions = Transaction.query();
});

在您的示例中,当您推送事务时,您无法确定模型是否已成功保存。

另一个提示:您可以在保存之前创建新事务,并直接从视图更新模型:

$scope.newTransaction = new Transaction();

$scope.addTransaction = function() {
    $scope.newTransaction.save( ...
}

在你看来的某个地方:

<input type="text" ng-model="newTransaction.name" />

ng-model 指令确保输入绑定到 newTransaction 模型的 name 属性。

于 2013-05-08T07:34:29.840 回答