Services, Factories, and Providers: Creating a Value Object

Craig McKeachie
InstructorCraig McKeachie

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

Creating your own services in AngularJS can be confusing. What are the differences between an AngularJS module's Service, Provider, Factory, and Value functions? This lesson shows how Angular's value function allows you to use register a plain JavaScript object as an AngularJS service.

[00:01] There are lots of ways to create objects in JavaScript. Sometimes, you need inheritance. Sometimes, you need privacy and reuse. Sometimes, you just need a plain old JavaScript object literal.

[00:11] I'll create one here called "droidValue." I'll give it a name property and initialize that to an empty string. We'll create a speak function and implement that to return, "Hi I am," and then concatenate on the name.

[00:31] To use this object, we'll create a droid variable and, then, give that a reference to the droidValue. You notice we don't have to do anything special, here. We don't need to invoke the droidValue object. It's already an object.

[00:50] We don't need to use the new keyword, here. We just simply need to make a reference to the object. Then, we can use the object. We can say, = 'bb-8,' and we can logout the droid speaking to the console. If I save this, I get, "Hi I am bb-8" over here.

[01:11] If I wanted to use this value object inside of an Angular application, I can switch over to my blank Angular application and paste the code into my app JS, here. To register this object with Angular, we call that value off of the Angular module, we give it a name, and we point at our object droidValue.

[01:33] We can simply ask for an instance of droid, here, and we'll get a reference to that droidValue object. We can work with the object. We can say and assign it bb-8, as we did outside of Angular.

[01:49] We also have a message property off of our DroidController. I can set that message property equal to the droid speak method. If I save that, we should see, "Hi I am bb-8," inside of the Angular page.

[02:08] To recap, there are a lot of fancy ways to create objects in JavaScript. Sometimes, you just need a plain object literal, as we have here.

[02:16] If that is the case, all you need is to call .value and give a reference to your object. Angular will know to dependency inject a reference to that object when you ask for it.