我可以在角每个控制器可用的功能? [英] Can I make a function available in every controller in angular?
问题描述
如果我有一个效用函数富
,我希望能够从任何地方打电话给我的 NG-应用$ C $内C>声明。有什么方法我可以在我的模块设置全局访问或者我需要将它添加到的范围在每一个控制器?
If I have a utility function foo
that I want to be able to call from anywhere inside of my ng-app
declaration. Is there someway I can make it globally accessible in my module setup or do I need to add it to the scope in every controller?
推荐答案
您基本上有两种选择,要么把它定义为一个服务,或者把它放在你的根范围。我建议你做一个服务出来,以避免污染根范围内。创建服务,并使其在您的控制器像这样可供选择:
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
如果这不是一个选择,你可以将它添加到根的范围是这样的:
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
这样,你的所有模板可以拨打 globalFoo()
,而无需将它传递给从控制器的模板。
That way, all of your templates can call globalFoo()
without having to pass it to the template from the controller.
这篇关于我可以在角每个控制器可用的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!