angular.js - 在angular中定义模块的全局变量有哪些方法?示例代码?

浏览:29日期:2023-01-26

问题描述

例如,

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

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

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

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

问题解答

回答1:

1.一般来说,是不建议在$rootScope上面绑定过多的变量,这样一来程序的可维护性就会变差;当然只是不建议,特殊情况特殊处理;比如网站的title标题可能要经常换,所以这个绑定在$rootScope还是个不错的选择。2.Angular提供了两种方法,一种方法就是你说的那个,还有就是下面的:

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

3.一般来说使用value和constant已经可以了。

1.我看你的情况应该是想在整个应用中使用这个函数,那么你可以写在服务中啊,Angular的Service就是为了提供全局公用的方法;上面的使用方法是为了可以使用一些外部的插件,或者配置一些应用的信息而使用的,我这边写了一个例子,你可以看看,传送门。

2.具体的代码可以看下面:

引入文件的顺序

<script src='https://www.6hehe.com/lib/angular.js'></script> <script src='https://www.6hehe.com/wenda/module.js'></script> <script src='https://www.6hehe.com/wenda/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(); }})();

相关文章: