Javascript 将用户定义的函数放在 Angular JS 的何处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12480400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:28:59  来源:igfitidea点击:

Where to put user defined functions in Angular JS?

javascriptmodel-view-controllerscopeangularjs

提问by Kyle Macey

In my view, I want to render:

在我看来,我想渲染:

<p>
  {{ say() }}
</p>

Where sayis defined as such:

其中say定义如下:

say = function() {
  return "Hello World";
}

I can define it in my controller:

我可以在我的控制器中定义它:

function TestCtrl($scope) {
  $scope.say = function() { ... };
}

But then it's only accessible within that controller.

但是它只能在该控制器内访问。

If I define the function outside the Angular file structure, it renders nothing. Same if I define it in my controllers.jsfile, but outside a controller function scope.

如果我在 Angular 文件结构之外定义函数,它不会渲染任何内容。如果我在我的controllers.js文件中定义它,但在控制器功能范围之外,也是如此。

Where is the proper place to put my function, so I can render it in any controller?

放置我的函数的正确位置在哪里,以便我可以在任何控制器中呈现它?

回答by Gloopy

One way is to create a servicewith the functions you want to share across multiple controllers. See this postfor more info.

一种方法是创建一个具有您想要在多个控制器之间共享的功能的服务。有关更多信息,请参阅此帖子

After you do so you can inject the service you created into any controller and access the say()function with code something like this:

执行此操作后,您可以将您创建的服务注入任何控制器并使用如下say()代码访问该功能:

function TestCtrl($scope, myService){
   $scope.say = myService.say;
}

Where you defined myServiceas:

您定义myService为:

angular.module('myApp', [])
    .factory('myService', function () {
        return {
            say: function () {
                return "Hello World";
            }
        }
    });

Here is a jsFiddlewith an example.

这是一个带有示例的jsFiddle