Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @id as passed to $resource?

Tags:

angularjs

$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.

like image 944
James Avatar asked Jul 09 '13 22:07

James


1 Answers

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.

like image 50
rGil Avatar answered Sep 21 '22 13:09

rGil