13

I am learning AngularJS and reading its API

Angular JS Resource

It says "If the parameter value is prefixed with @ then the value of that parameter is extracted from the data object " with code example:

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

I am so slow that after the example I still don't get what the prefixed @ means/does. Could someone please give me some examples With and Without the @ and elaborate it? Thanks...

1 Answer 1

10

Sure.

It means that the value of :userId in your url will be replaced with the id property from the user object when that property is required.

So when is it required? Its required when you are doing something to an existing user, like geting one, updating one. It is not required when you create a user.

In most cases, you will want to have at least one param prefixed with @ in your REST url that resource uses (probably the object id). If you dont have one, that means that in order for you to save an instance of an object, you dont need to know anything about where its stored. This implies that its a singleton object. Maybe like a settings object.

Here is your long awaited example:

var User = $resource('/user/:userId/:dogName', {userId:'@id', dogName:@dog});
User.get({userId:123, dog:'Matt'}, function() { .. })

will produce the request: GET /user/123/Matt

Sign up to request clarification or add additional context in comments.

4 Comments

I just tried the code you suggested - it produced a subtly different GET request: /user/123/?dog=Matt. How does angular decide whether the properties are sent as GET parameters (e.g. dog here) or as part of the URL (userId here)? In my case I wanted a user id sent as part of the URL, but with no subsequent parameter. Can that be done?
sorry, I haven't used angular in months. I don't know.
@Racing Tadpole. The resulting ?dog=Matt is due to the fact that the parameter sent is dog and not dogName. If it were dogName, you would get /user/123/Matt.
I found the answer in stackoverflow.com/a/17560529/75113 to be more clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.