我的$rootScope上有一个函数
myApp.run(['$rootScope','$location', function($rootScope,$location){
$rootScope.myFunction = function(){
//do something
};
}]);我需要把myFunction搬到angular.constant。我该怎么做?
发布于 2015-10-13 10:53:00
只需将其注册为constant,就可以使用angular.constant(name, function)
angular.module('example', []);
angular.module('example')
.constant('myFunction', myFunction);
function myFunction() {
return 'foobar';
}
angular.module('example')
.controller('ExampleController', ['myFunction', ExampleController]);
function ExampleController(myFunction) {
this.text = myFunction();
}<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="example">
<div ng-controller="ExampleController as vm">{{vm.text}}</div>
</div>
但是,尽管您可以将任何内容注册为constant (函数、对象.),但请注意,它的目的是保存很少的应用程序范围的常量,比如主机域。对于实际的业务逻辑,我总是建议使用angular.service,将功能分组为有意义的模块。
https://stackoverflow.com/questions/33100548
复制相似问题