在那里把用户自定义函数的角度JS? [英] Where to put user defined functions in Angular JS?
问题描述
在我看来,我想渲染:
<p>
{{ say() }}
</p>
其中,说
的定义是这样的:
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.
如果我定义角度文件结构外的函数,它呈现什么。相同的,如果我把它定义在我的 controllers.js
文件,但外部的控制器功能范围。
If I define the function outside the Angular file structure, it renders nothing. Same if I define it in my controllers.js
file, but outside a controller function scope.
在哪里把我的功能适当的位置,这样我就可以在任何控制器呈现呢?
Where is the proper place to put my function, so I can render it in any controller?
推荐答案
的一种方法是创建具有一个服务你想要的功能在多个控制器共享。请参见这个帖子获取更多信息。
One way is to create a service with the functions you want to share across multiple controllers. See this post for more info.
在你做,你可以注入你到任何控制器创建的服务,并访问说()
与code这样的功能:
After you do so you can inject the service you created into any controller and access the say()
function with code something like this:
function TestCtrl($scope, myService){
$scope.say = myService.say;
}
您定义的为myService
为:
angular.module('myApp', [])
.factory('myService', function () {
return {
say: function () {
return "Hello World";
}
}
});
下面是一个的jsfiddle 的一个例子。
Here is a jsFiddle with an example.
这篇关于在那里把用户自定义函数的角度JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!