我可以在 angular 的每个控制器中提供一个功能吗? [英] Can I make a function available in every controller in angular?

查看:27
本文介绍了我可以在 angular 的每个控制器中提供一个功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个实用函数 foo,我希望能够从我的 ng-app 声明中的任何地方调用它.有什么办法可以让它在我的模块设置中全局访问,还是需要将它添加到每个控制器的范围内?

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.

这篇关于我可以在 angular 的每个控制器中提供一个功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆