Closed MrOutput closed 8 years ago
Use factory instead of service Angular is singleton for factory and services...
(function() {
angular
.module('App')
.factory('servicePerson', servicePerson);
function servicePerson() {
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.alert = function() {
alert('Name:' + this.name +' Age:'+ this.age);
}
var service = {
newPerson : newPerson
}
return service;
function newPerson(name, age){
return new Person(name, age);
}
}
}) ();
In controller
(function() {
angular
.module('App')
.controller('DemoController', DemoController);
DemoController.$inject = ['servicePerson'];
function DemoController(servicePerson) {
var a = servicePerson.newPerson('rafael', 22);
a.alert();
var Demo = this;
Demo.title = 'Demo';
}
}) ();
That's just not right friend.
Work for me. http://jsfiddle.net/sava/612phm6n/
@mroutput, yeah, but what's is the best way?
@sava-vidakovic. for me too
this is just how they work :)
I am not sure if the angular team had mixed ideas about services and factories. But the code and ideas mentioned in the services section don't add up, not even on angular's site. If service registration takes a constructor function as the second argument, and its suppose to be invoked as a constructor would, with the
new
keyword, then why can't I treat it as a true constructor passing in parameters?Service
Controller