angular.js - 在angular中定义模块的全局变量有哪些方法?示例代码?
滿天的星座
滿天的星座 2017-05-15 16:55:17
0
1
607

例如,

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

再例如,绑定在$rootScope上面。

感觉自己脑子里对这些有些模糊,想讨论一下这个主题。

https://docs.angularjs.org/api/ng/type/angular.Module
这个页面里的api都怎么用,感觉只看文档不是很明白。

滿天的星座
滿天的星座

reply all(1)
大家讲道理

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();
    }
})();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!