johnpapa / angular-styleguide

Angular Style Guide: A starting point for Angular development teams to provide consistency through good practices.
http://johnpapa.net
MIT License
23.86k stars 4.15k forks source link

service guide doesnt work #754

Closed MrOutput closed 8 years ago

MrOutput commented 8 years ago

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";
    }
})();
phpedinei commented 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';
    }
}) ();
MrOutput commented 8 years ago

That's just not right friend.

sava-vidakovic commented 8 years ago

Work for me. http://jsfiddle.net/sava/612phm6n/

phpedinei commented 8 years ago

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

@sava-vidakovic. for me too

johnpapa commented 8 years ago

this is just how they work :)