-
-
Save ThomasBurleson/6265249 to your computer and use it in GitHub Desktop.
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 | |
}()) |
$asyncService is another instance (of a Class, object, function) that was
- registered with Angular (via
.service()
or.factory()
, and then later... - instantiated by the Angular engine during the app bootstrapping processes
// register AsyncService to create instance of $asyncService
angular.module( "myApp.myModel", [ ])
.service( "$asyncService", AsyncService)
.service('myModel', MyModel);
This instance $asyncService
is then injected as an parameter to the function MyModel( )
invocation; which creates an instance of myModel
.
See how Angular allows you to create beans/services, define dependencies, and auto-injects those as needed?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above code appears to be wrong. Here are some proposed fixes:
Also here are some additional feedback items:
angular.service()
be used and fails ifangular.factory()
is used by mistake. Since.service()
calls use thenew
operatorthis
is scoped for the new instance..factory()
, however, does not use thenew
operator sothis
will not be valid.Here is a solution that solves all of the above issues: