search

Home  >  Q&A  >  body text

angular.js - What are the ways to define global variables of a module in angular? Sample code?

For example,

angular.module('xxx',[])
    .value();

Another example is binding on $rootScope.

I feel like my mind is a little fuzzy on this and I want to discuss this topic.

https://docs.angularjs.org/api/ng/type/angular.Module
How to use the API on this page, I feel like I don’t understand it just by looking at the documentation.

滿天的星座滿天的星座2841 days ago681

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-05-15 16:57:17

    1. Generally speaking, it is not recommended but it is still a good choice in $rootScope上面绑定过多的变量,这样一来程序的可维护性就会变差;当然只是不建议,特殊情况特殊处理;比如网站的title标题可能要经常换,所以这个绑定在$rootScope.
    2. Angular provides two methods, one is the one you mentioned, and the other is the following:

        (function() {
        'use strict';
    
        angular
            .module('app')
            .constant('toastr', toastr)
            .constant('moment', moment);
    })();

    3. Generally speaking, it is enough to use valueconstant.


    1. I think in your case you want to use this function in the entire application, then you can write it in the service. Angular's Service is to provide global public methods; the above usage method is to use some External plug-ins, or used to configure some application information, I have written an example here, you can take a look, Portal.

    2. The specific code can be seen below:

    The order of importing files

        <script src="../lib/angular.js"></script>
        <script src="module.js"></script>
        <script src="app.js"></script>

    index.html

        <body ng-app="MyApp">
            <h1>constant</h1>
            <p ng-controller="MyController as vm">
                <p>
                    {{vm.test}}
                </p>
                <p>{{vm.my_key}}</p>
            </p>
        </body>

    module.js

        (function(window){
        // ..
        // exports
    
        var Test = {
            hello: function(){
                console.log('hello');
            }
        };
    
        window.Test = Test;
    
    })(window);

    app.js

        (function(){
    
        angular.module('MyApp', [])
            .constant('Test', Test)
            .constant('MyKey', 'q123nasbd12y38basd237y')
            .controller('MyController', MyController)
            .service('Service', Service);
    
    
        MyController.$inject = ['Test', 'Service', 'MyKey'];
        Service.$inject = [];
    
    
        function Service(){
            var service = {
                info: info
            };
    
            return service;
    
            function info(){
                return 'info';
            }
        }
    
        function MyController(Test, Service, MyKey){
            var vm = this;
            vm.test = Service.info();
            vm.my_key = MyKey;
            Test.hello();
        }
    })();

    reply
    0
  • Cancelreply