[AngularJS] Services, Factories, and Providers -- value & Providers

Creating a Value Object

Sometimes you have javascript object defined:

    //value object
    var droidValue = {
        name: '',
        speak: function () {
            return "Hi I am " + this.name;
        }
    };
    
    var droid = droidValue;
    droid.name = 'bb-8';
    console.log(droid.speak());

If want to use this object in AngularJS, can use 'value':

//angularjs
(function () {
    "use strict";

    //value object
    var droidValue = {
        name: '',
        speak: function () {
            return "Hi I am " + this.name;
        }
    };


    angular.module('app', [])
        .value('droid', droidValue)
        .controller('DroidController', DroidController)

    function DroidController(droid) {
        var droidCtrl = this;
        droid.name = 'bb-8';
        droidCtrl.message = droid.speak();

    }


})();

Creating a Provider

//angularjs
(function () {
    "use strict";

    //module pattern (configurable per app)
    function droidProvider() {
        var greeting = '';
        return {
            configure: function (settings) {
                greeting = settings.greeting;
            },
            $get: function () {
                return {
                    name: '',
                    speak: function () {
                        return greeting + this.name;
                    }

                };
            }

        };
    }


    angular.module('app', [])
        .config(function (droidProvider) {
            droidProvider.configure({greeting: "Greetings I am "});

        })
        .provider('droid', droidProvider)
        .controller('DroidController', DroidController);

    function DroidController(droid) {
        var droidCtrl = this;
        droid.name = "ig-88";
        droidCtrl.message = droid.speak();

    }


})();

Important to understand:

  • Each provider should have a $get function
  • When you use config black to configure provider, it actually invoke droidProvider() function and then get the return object back
return {
            configure: function (settings) {
                greeting = settings.greeting;
            },
            $get: function () {
                return {
                    name: '',
                    speak: function () {
                        return greeting + this.name;
                    }

                };
            }

        };
  • When you inject provider into controller, it actually call the $get function inside the provider, and then return the object inside $get() function
return {
                    name: '',
                    speak: function () {
                        return greeting + this.name;
                    }

                };
原文地址:https://www.cnblogs.com/Answer1215/p/5045307.html