Creating a Service:
Before actual create a angular service, first create a constructor in Javascript:
// constructor Function function Droidservice () { this. Name = '; } function () { returnthis. name; };
Then the we want to the use of this constutor function, you need to the new an instance:
var New Droidservice (); = ' R2-d2 '; Console.log (Droid.speak ());
What's need to understand, where do new opration, under the hook, Javascript does tow thing for you:
function Droidservice () { // var this = {} this . Name = '; // return this; }
First is the Var a new this object and then return the This object.
Angular Service is a constructor function.
//constructor Function functionDroidservice () { This. Name = ' '; } DroidService.prototype.speak=function () { return"Hi I AM" + This. Name; }; Angular.module (' App ', []). Service (' Droid ', Droidservice). Controller (' Droidcontroller ', Droidcontroller); functionDroidcontroller (Droid) {varDroidctrl = This; Droid.name= ' R2-d2 '; Droidctrl.message=Droid.speak (); }
When you create a service in angular, it helps to ' new ' the constructor (service) and then inject this instance whenever Want to use it.
Creating a Factory:
You can create a function which return an object:
function droidfactory () { function speakingprivately () { return this . Name; return { "', speak:speakingprivately }; }
This was called reaveling Modular Partten, because you can choose which function or props to being public or privat E by include those into return object.
Then you just need to invoke the function and you can get the object.
var droid = droidfactory (); = ' C3-po '; Console.log (Droid.speak ());
Angular Factory is a function which return an object. (no constructor fucntion, no new Opreation):
//revealing module pattern functiondroidfactory () {functionspeakingprivately () {return"Hi I AM" + This. Name; } return{name:‘‘, speak:speakingprivately}; } angular.module (' App ', []). Factory (' Droid ', Droidfactory). Controller (' Droidcontroller ', Droidcontroller); functionDroidcontroller (Droid) {varDroidctrl = This; Droid.name= ' C3-po '; Droidctrl.message=Droid.speak (); }
When you create a factory, Angular'll help to invoke the function so when you inject into controller, you'll get the O Bject back.
[AngularJS] Services, factories, and Providers--Service vs Factory