例如,
angular.module('xxx',[])
.value();
再例如,綁定在$rootScope上面。
感覺(jué)自己腦子里對(duì)這些有些模糊,想討論一下這個(gè)主題。
https://docs.angularjs.org/api/ng/type/angular.Module
這個(gè)頁(yè)面里的api都怎么用,感覺(jué)只看文檔不是很明白。
1.一般來(lái)說(shuō),是不建議在$rootScope
上面綁定過(guò)多的變量,這樣一來(lái)程序的可維護(hù)性就會(huì)變差;當(dāng)然只是不建議,特殊情況特殊處理;比如網(wǎng)站的title
標(biāo)題可能要經(jīng)常換,所以這個(gè)綁定在$rootScope
還是個(gè)不錯(cuò)的選擇。
2.Angular提供了兩種方法,一種方法就是你說(shuō)的那個(gè),還有就是下面的:
(function() {
'use strict';
angular
.module('app')
.constant('toastr', toastr)
.constant('moment', moment);
})();
3.一般來(lái)說(shuō)使用value
和constant
已經(jīng)可以了。
1.我看你的情況應(yīng)該是想在整個(gè)應(yīng)用中使用這個(gè)函數(shù),那么你可以寫(xiě)在服務(wù)中啊,Angular的Service就是為了提供全局公用的方法;上面的使用方法是為了可以使用一些外部的插件,或者配置一些應(yīng)用的信息而使用的,我這邊寫(xiě)了一個(gè)例子,你可以看看,傳送門(mén)。
2.具體的代碼可以看下面:
引入文件的順序
<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();
}
})();