Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

angularjs - What is @id as passed to $resource?

$resource("/entries/:id", {id: "@id"}, {update: {method: "PUT"}})

What is @id?

On the $resource doc page someone says this below, but I still don't understand.

If the parameter value is prefixed with @ then the value of that parameter is extracted from the data object (useful for non-GET operations)." The data object here refers to the postDataobject if non-GET "class" action is used, or the instance itself if non-GET instance action is used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand this correctly, and I may not, the parameter {id: @id} is an illustration of another way to supply your url variable with a piece of data.

Given this method:

var myResource = $resource("/posts/:theName", 
                           {theName: '@petName'},
                           {enter : {
                                      method: "POST", 
                                      isArray: false
                                     }
                            });

If I have an attribute "petName" in the data that I'm posting, the value of that attribute will be placed in :theName variable in my url. Imagine the post data being {"petType": "cat", "petName": "Spot"}, the url will read "/posts/Spot". In my mind, the @ means "attribute" of the object to be posted.

Take away the @ from that value, and the url variable will directly reference the value in that resource parameter:

{theName: 'petName'} //no "@"
// url output ---->   '/posts/petName'

.

Here is the chain of references:

//url var--> //$resource param {..}  --->//Object to be posted
:theName---> {theName ----> @petName ---> {petName---> "Spot"

It only took 5 steps to get "Spot" into the url!

.

Example of a resource instance using the above example:

var postData = new myResource();
    postData.petType = "cat";
    postData.petName = "Spot";
    postData.$enter({}, function(data){
        $scope.data = data;
    })
    // url to post to will be '/posts/Spot', postData object will be 
    //  {"petType":"cat", "petName:"Spot"}

On a side note, the docs can be very confusing. Have you ever taken a difficult course and the professor was a brilliant man who barely spoke your language? Yup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...