No estoy seguro de si el equipo de angular tenía ideas encontradas sobre servicios y fábricas. Pero el código y las ideas mencionadas en la sección de servicios no cuadran, ni siquiera en el sitio de angular. Si el registro del servicio toma una función de constructor como segundo argumento, y se supone que debe invocarse como lo haría un constructor, con la palabra clave new
, ¿por qué no puedo tratarlo como un verdadero constructor pasando parámetros?
(function () {
angular
.module("App")
.service("Person", Person);
//angular wants my parameters to be injectables.
function Person(name, age) {
this.name = name;
this.age = age;
}
})();
(function () {
angular
.module("App")
.controller("DemoController", DemoController);
DemoController.$inject = ["Person"];
function DemoController(Person) {
var a = new Person("rafael", 22);// ERROR
var Demo = this;
Demo.title = "Demo";
}
})();
Utilice la fábrica en lugar del servicio
Angular es singleton para fábrica y servicios ...
(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);
}
}
}) ();
En controlador
(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';
}
}) ();
Eso no es amigo correcto.
Trabaja para mi.
http://jsfiddle.net/sava/612phm6n/
@mroutput , sí, pero ¿cuál es la mejor manera?
@ sava-vidakovic. para mí también
así es como funcionan :)
Comentario más útil
Trabaja para mi.
http://jsfiddle.net/sava/612phm6n/