Creating common controller functions

前端 未结 2 1331
南旧
南旧 2020-11-27 14:55

How do I create some sort of utils bundle that would be accessible from all my controllers?

I have this route code in my main module:

\'use strict\';         


        
2条回答
  •  执念已碎
    2020-11-27 15:10

    Just to update previous answer (which only define what factory is), there are 3 ways to inject dependencies (define common code) in AngularJS:

    • Providers
    • Factories
    • Services

    I will not talk much about provider because it is a more laborious method for dependency injection. However, this page explains very well how they work.


    Technically, service and factory are used for the same thing. It turns out, a service is a constructor function whereas a factory is not.

    From this post:

    module.service( 'serviceName', function );
    

    When declaring serviceName as an injectable argument you will be provided with an instance of the function.

    module.factory( 'factoryName', function );
    

    When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.


    You can use the one you prefer and obtain the same result.

    Here is two codes doing exactly the same thing through service first, and then factory:

    Service syntax

    app.service('MyService', function () {
      this.sayHello = function () {
        console.log('hello');
      };
    });
    

    Factory syntax

    app.factory('MyService', function () {
      return {
        sayHello: function () {
          console.log('hello');
        }
      }
    });
    

提交回复
热议问题