在Angular JS中放置用户定义函数的位置?

Kyl*_*cey 35 javascript model-view-controller scope angularjs

在我看来,我想呈现:

<p>
  {{ say() }}
</p>
Run Code Online (Sandbox Code Playgroud)

在哪里say定义如下:

say = function() {
  return "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

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

function TestCtrl($scope) {
  $scope.say = function() { ... };
}
Run Code Online (Sandbox Code Playgroud)

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

如果我在Angular文件结构之外定义函数,它什么都不呈现.如果我在我的controllers.js文件中定义它,但在控制器函数范围之外,则相同.

放置我的功能的适当位置在哪里,所以我可以在任何控制器中渲染它?

Glo*_*opy 48

一种方法是使用要在多个控制器之间共享的功能创建服务.有关详细信息,请参阅此帖子.

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

function TestCtrl($scope, myService){
   $scope.say = myService.say;
}
Run Code Online (Sandbox Code Playgroud)

你定义的地方myService是:

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

这是一个jsFiddle的例子.

  • 仅供参考,另一种语法(如果我只需要构造函数,我更喜欢看/读'服务'而不是'工厂'):. service('myService',function(){this.say = function(){return"你好,世界"; } }); (5认同)