【问题标题】:AngularJS: How to pass values from Controller to Service Method?AngularJS:如何将值从控制器传递到服务方法?
【发布时间】:2013-05-31 15:23:28
【问题描述】:

我有一个依赖于TransactionService 的控制器。其中一种方法是

$scope.thisMonthTransactions = function () {
    $scope.resetTransactions();
    var today = new Date();
    $scope.month = (today.getMonth() + 1).toString();
    $scope.year = today.getFullYear().toString();
    $scope.transactions = Transaction.getForMonthAndYear();
};

TransactionService 看起来像

angular.module('transactionServices', ['ngResource']).factory('Transaction', function ($resource, $rootScope) {
    return $resource('/users/:userId/transactions/:transactionId',
        // todo: default user for now, change it
        {userId: 'bd675d42-aa9b-11e2-9d27-b88d1205c810', transactionId: '@uuid'},
        {
            getRecent: {method: 'GET', params: {recent: true}, isArray: true},
            getForMonthAndYear: {method: 'GET', params: {month: 5, year: 2013}, isArray: true}
        });
});

如您所见,getForMonthAndYear 方法依赖于两个参数 monthyear,它们现在被硬编码为 params: {month: 5, year: 2013}。如何从我的控制器传递这些数据?

我尝试在TransactionService 中注入rootScope,但这并没有帮助(意味着我可能不知道如何使用它)。

另外Angular ngResource documentation 不推荐任何方式来执行此操作。

有人可以在这里指导吗?

更新
我的控制器看起来像

function TransactionsManagerController($scope, Transaction) {

    $scope.thisMonthTransactions = function () {
        $scope.resetTransactions();
        var today = new Date();
        $scope.month = (today.getMonth() + 1).toString();
        $scope.year = today.getFullYear().toString();

        var t = new Transaction();
        $scope.transactions = t.getForMonthAndYear({month: $scope.month});
    };
}

我将服务方法更改为

getForMonthAndYear: {method: 'GET', params: {month: @month, year: 2013}, isArray: true}

我看了一下console.log,上面写着

Uncaught SyntaxError: Unexpected token ILLEGAL transaction.js:11
Uncaught Error: No module: transactionServices 

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-service


    【解决方案1】:

    我遇到了同样的问题,我最终从我的服务返回参数化函数,所以服务看起来像那样

    factory('MyService', function($resource) {
        return {
            id: function(param) { return $resource('/api/'+param+'/:id', {id: '@id'}); },
            list: function(param) { return $resource('/api/'+param); },
            meta: function(param) { return $resource('/api/meta/'+param); }
        }
    })
    

    并从控制器调用服务:

    $scope.meta = MyService.meta('url_param').query();
    

    不确定这是最干净的 angular.js 解决方案,但它有效!

    【讨论】:

      【解决方案2】:

      一种方法是将服务注入您的控制器:

      angular.controller('controllerName', 
       ['$scope', 'Transaction',
         function($scope, transactionService) {
            ...
         }
      ]);
      

      然后您可以通过 transactionService 参数访问您的服务实例。

      编辑

      看看这个fiddle告诉我这是否足够接近你想要做的事情

      【讨论】:

      • 你能告诉我怎么做吗?我刚刚尝试并更新了我的问题
      • @daydreamer:您的事务服务位于一个名为“transactionServices”的模块中。确保定义控制器的模块将其指定为其依赖项。 angular.module('myCtrlModule', ['transactionServices']).controller(...
      【解决方案3】:

      只有在没有提供默认值时调用需要具有默认值时,才需要在资源构造函数中定义参数。传入该方法的任何参数都作为查询参数附加,无论它是否定义了默认值。 '@' 表示 params 值被 JSON 响应中返回的值替换,因此您的 @uuid 有意义,但不是您的 @month。

      就个人而言,我会像这样创建资源:

      $resource('/users/:userId/transactions/:transactionId',
          // todo: default user for now, change it
          {userId: 'bd675d42-aa9b-11e2-9d27-b88d1205c810', transactionId: '@uuid'},
          {
              getRecent: {method: 'GET', params: {recent: true}, isArray: true},
              getForMonthAndYear: {method: 'GET', isArray: true}
          });
      

      然后根据需要通过传入查询变量来添加它们。(创建特殊的方法名称很好但不是必需的,因此在下面显示两种方式。)

      var t = new Transaction();
      $scope.recentTransactions = t.$get({recent:true}) //results in /users/bd675d42-aa9b-11e2-9d27-b88d1205c810/transactions/?recent=true
      $scope.recentTransactions = t.$getRecent(); //same thing as above
      $scope.transactions = t.$get({month: $scope.month, year: $scope.year}); //results in /users/bd675d42-aa9b-11e2-9d27-b88d1205c810/transactions/?month=5&year=2013
      $scope.transactions = t.$getForMonthAndYear({month: $scope.month, year: $scope.year}); //same as above... since no defaults in constructor, always pass in the params needed
      

      【讨论】:

      • 我认为他的问题不在于 $resource,而在于控制器和服务之间的交互
      猜你喜欢
      • 2016-04-18
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多