Confused about Service vs Factory

后端 未结 20 2845
轻奢々
轻奢々 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:38

    live example

    " hello world " example

    with factory / service / provider :

    var myApp = angular.module('myApp', []);
     
    //service style, probably the simplest one
    myApp.service('helloWorldFromService', function() {
        this.sayHello = function() {
            return "Hello, World!"
        };
    });
     
    //factory style, more involved but more sophisticated
    myApp.factory('helloWorldFromFactory', function() {
        return {
            sayHello: function() {
                return "Hello, World!"
            }
        };
    });
        
    //provider style, full blown, configurable version     
    myApp.provider('helloWorld', function() {
        // In the provider function, you cannot inject any
        // service or factory. This can only be done at the
        // "$get" method.
     
        this.name = 'Default';
     
        this.$get = function() {
            var name = this.name;
            return {
                sayHello: function() {
                    return "Hello, " + name + "!"
                }
            }
        };
     
        this.setName = function(name) {
            this.name = name;
        };
    });
     
    //hey, we can configure a provider!            
    myApp.config(function(helloWorldProvider){
        helloWorldProvider.setName('World');
    });
            
     
    function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
        
        $scope.hellos = [
            helloWorld.sayHello(),
            helloWorldFromFactory.sayHello(),
            helloWorldFromService.sayHello()];
    }​
    

提交回复
热议问题