Angular-styleguide: service guide doesnt work

Created on 25 Jul 2016  ·  5Comments  ·  Source: johnpapa/angular-styleguide

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

(function () {
    angular
        .module("App")
        .service("Person", Person);

    //angular wants my parameters to be injectables.
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
})();

Controller

(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";
    }
})();
question

Most helpful comment

All 5 comments

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.

@mroutput, yeah, but what's is the best way?

@sava-vidakovic. for me too

this is just how they work :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

annabellor picture annabellor  ·  9Comments

andreshg112 picture andreshg112  ·  3Comments

sgbeal picture sgbeal  ·  7Comments

jusefb picture jusefb  ·  9Comments

amiceli picture amiceli  ·  7Comments