Annotary
Sort
angularjs - confused about service vs factory - Stack Overflow

angularjs - confused about service vs factory - Stack Overflow

stackoverflow.com
yehosef shapiro yehosef shapiro
3 years ago

There is also a way to return a constructor function so you can return newable classes in factories, like this:

function MyObjectWithParam($rootScope, name) {
  this.$rootScope = $rootScope;
  this.name = name;
}
MyObjectWithParam.prototype.getText = function () {
  return this.name;
};

App.factory('MyObjectWithParam', function ($injector) {
  return function(name) { 
    return $injector.instantiate(MyObjectWithParam,{ name: name });
  };
}); 

So you can do this in a controller, which uses MyObjectWithParam:

var obj = new MyObjectWithParam("hello"),

See here the full example:
http://plnkr.co/edit/GKnhIN?p=preview

And here the google group pages, where it was discussed:
https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/b8hdPskxZXsJ

good use of newable for factories
Cancel
Sort
Iffy Can: Angular service or factory?

Iffy Can: Angular service or factory?

iffycan.blogspot.co.il
yehosef shapiro yehosef shapiro
3 years ago
says you new a service
If you want your function to be called like a normal function, use factory. If you want your function to be instantiated with the new operator, use service. If you don't know the difference, use factory.
says you new a service
Cancel
Sort

angularjs - angular.service vs angular.factory - Stack Overflow

stackoverflow.com
yehosef shapiro yehosef shapiro
3 years ago

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

says you new a factory
Cancel
Loading...