Confused about Service vs Factory

后端 未结 20 2771
轻奢々
轻奢々 2020-11-22 08:49

As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this

20条回答
  •  误落风尘
    2020-11-22 09:33

    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

提交回复
热议问题