Last active
December 21, 2015 04:39
-
-
Save joelhooks/6251511 to your computer and use it in GitHub Desktop.
Short example of how to declare services in AngularJS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//from most to least verbose, but it is all the same in the end. | |
(function() { | |
var module = angular.module("myApp.myModel", []); | |
var MyModel = function MyModel() { | |
this.asyncService = null; | |
this.someApi = function() { | |
return this.asyncService.getStuff(); //promise? | |
} | |
} | |
var myModelProvider = Class.extend({ | |
model: new MyModel(); | |
$get: ['asyncService', function (asyncService) { | |
model.asyncService = asyncService; //dependency injection | |
return model; //resolved for the lifetime of app | |
}] | |
}); | |
modules.provider('myModel', myModelProvider); | |
}()) | |
// or | |
(function() { | |
var module = angular.module("myApp.myModel", []); | |
var MyModel = function MyModel(asyncService) { | |
this.asyncService = null; | |
this.someApi = function() { | |
return this.asyncService.getStuff(); //promise? | |
} | |
} | |
module.factory('myModel', ['asyncService', function (asyncService) { | |
//could do some stuff here | |
return new MyModel(asyncService); | |
}]); | |
}()) | |
// or | |
(function() { | |
var module = angular.module("myApp.myModel", []); | |
var MyModel = function MyModel(asyncService) { | |
this.asyncService = null; | |
this.someApi = function() { | |
return this.asyncService.getStuff(); //promise? | |
} | |
} | |
module.service('myModel', ['$asyncService', MyModel]); //most simple option | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@joelhooks
Just working for you as a
second pair of eyes
;-).BTW, rumour/documentation implies that a
factory
creates asingleton
. Since a service (which usesnew
) does not necessarily create a singleton, here is a way to easy force/manage singletons regardless of.factory()
or.service()
instantiations.