1

I'm working on a service as a model in AngulaJS. I use a factory nad I want to use the angular.extend() thing to add attributes/properties to the $resource object.

The problem is that I can't access attributes added with this :

var myObject = $resource(...);

angular.extend(myObject.prototype, {
    hi : "hi",
    findFriend : function(){ console.log("You are all alone...") }
}

I'm not able to access "hi" or "findFriend" in my controller nor in the factory with a console.log().

But if I do this :

var myObject = $resource(...);

angular.extend(myObject, {
    hi : "hi",
    findFriend : function(){console.log("It works"}
}

Then I'm able to access those attributes. If the good practice is the second one, then what is the difference with :

var myObject = $resource(...);
myObject.hi = "hi";
myObject.findFriend("It works");

?

I read the documentation and followed this article to build my model.

Can someone explain why one work and not the other ? Why it seems to be different from the article ?

Thank you :)

1 Answer 1

1

It is because your var myObject is not an instance of a class so extending the prototype will add method for instance not for class. $resource return a "class" object so you need to instanciate an instance of myObject by using new myObject().

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

2 Comments

Thanks for the answer. What should I do so, is it bad to stay with the myObject = $resource() then modify with angular.Extend(myObject, ...) ?
No it is not bad, but you are not doing OOP, and it suggest that you instantiate your class.

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.