AngularJS : What is a factory?

前端 未结 4 2025
误落风尘
误落风尘 2020-12-12 09:37

I\'ve been doing a lot of work on Angular.js and overall I find it to be an interesting and powerful framework.

I know there have been a lot of discussio

4条回答
  •  难免孤独
    2020-12-12 09:59

    From what I understand they are all pretty much the same. The major differences are their complexities. Providers are configurable at runtime, factories are a little more robust, and services are the simplest form.

    Check out this question AngularJS: Service vs provider vs factory

    Also this gist may be helpful in understanding the subtle differences.

    Source: https://groups.google.com/forum/#!topic/angular/hVrkvaHGOfc

    jsFiddle: http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/

    author: Pawel Kozlowski

    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()];
    }​
    

提交回复
热议问题