AngularJS:如何将值从Controller传递到Service Method?

day*_*mer 16 javascript angularjs angularjs-service angularjs-scope

我有一个依赖于a的控制器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();
};
Run Code Online (Sandbox Code Playgroud)

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}
        });
});
Run Code Online (Sandbox Code Playgroud)

正如你所看到的方法getForMonthAndYear取决于两个参数monthyear,现在正好是硬编码params: {month: 5, year: 2013}.如何从控制器传递此数据?

我试过注射rootScopeTransactionService,但这并没有帮助(意思是我不知道该怎么可能使用它).

此外,Angular ngResource文档不建议以任何方式执行此操作.

有人可以在这里指导吗?

更新
我的控制器看起来像

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});
    };
}
Run Code Online (Sandbox Code Playgroud)

我将服务方法更改为

getForMonthAndYear: {method: 'GET', params: {month: @month, year: 2013}, isArray: true}
Run Code Online (Sandbox Code Playgroud)

我看着console.log它,它说

Uncaught SyntaxError: Unexpected token ILLEGAL transaction.js:11
Uncaught Error: No module: transactionServices 
Run Code Online (Sandbox Code Playgroud)

Luk*_*kus 5

只有在没有提供调用时需要具有默认值时,才需要在资源构造函数中定义params.无论是否定义了默认值,传入方法的任何参数都将作为查询参数附加.'@'表示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}
    });
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)


gru*_*gru 5

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

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); }
    }
})
Run Code Online (Sandbox Code Playgroud)

并从控制器调用服务:

$scope.meta = MyService.meta('url_param').query();
Run Code Online (Sandbox Code Playgroud)

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