最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS - Controller resource call not passing parameters to service factory? - Stack Overflow

programmeradmin2浏览0评论

In AngularJS, I'm trying to pass a parameter in a controller call to a service factory. However, I can't seem to get the parameter passed. The function always passes what I set to be the default in the service. And if I don't include the default, it doesn't pass anything.

For example, my code looks similar to:

Controller

...
Room.enter({room_id: '5'/*$scope.room_id*/}, function(return_data)
    {
        //Callback function stuff.
        ...
    }
...

Services

...
services.factory('Room', ['$resource',
    function($resource)
        {
            return $resource('/room/:room_id', {}, {
                    enter: {method: 'PUT', params:{room_id:'-1'}}
        });
    }
]);
...

This way the http resource "/room/-1" is called even though I am trying to pass 5.

If I remove the params part of the "enter" method, then "/room" is all that is called. No params are passed at all.

Any suggestions as to what I'm doing wrong? Thank you much!

In AngularJS, I'm trying to pass a parameter in a controller call to a service factory. However, I can't seem to get the parameter passed. The function always passes what I set to be the default in the service. And if I don't include the default, it doesn't pass anything.

For example, my code looks similar to:

Controller

...
Room.enter({room_id: '5'/*$scope.room_id*/}, function(return_data)
    {
        //Callback function stuff.
        ...
    }
...

Services

...
services.factory('Room', ['$resource',
    function($resource)
        {
            return $resource('/room/:room_id', {}, {
                    enter: {method: 'PUT', params:{room_id:'-1'}}
        });
    }
]);
...

This way the http resource "/room/-1" is called even though I am trying to pass 5.

If I remove the params part of the "enter" method, then "/room" is all that is called. No params are passed at all.

Any suggestions as to what I'm doing wrong? Thank you much!

Share Improve this question asked Feb 20, 2014 at 15:47 golmschenkgolmschenk 12.5k21 gold badges84 silver badges144 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Try

services.factory('Room', ['$resource',
    function($resource)
        {
            return $resource('/room/:room_id', {}, {
                enter: {method: 'PUT', params:{room_id:'@room_id'}}
        });
    }
]);

Edit:

Your parameters are passed as an object. Therefore, '@room_id' means that the value of the room_id property of the object passed should be extracted.

Note that the names must not match. In your controller, you could as well say

Room.enter({id: '5'}...

and get the value of the parameter in your service as

..., params:{room_id:'@id'}

发布评论

评论列表(0)

  1. 暂无评论