Javascript 创建通用控制器功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11324202/
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-24 05:26:43  来源:igfitidea点击:

Creating common controller functions

javascriptangularjswebangularjs-service

提问by Shlomi Schwartz

How do I create some sort of utils bundle that would be accessible from all my controllers?

如何创建某种可从我的所有控制器访问的 utils 包?

I have this route code in my main module:

我的主模块中有这个路由代码:

'use strict';

angular.module('lpConnect', []).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/home', {template: 'views/home.html', controller: HomeCtrl}).
        when('/admin', {template: 'views/admin.html', controller: AdminCtrl}).
        when('/connect', {template: 'views/fb_connect.html', controller: MainAppCtrl}).
        otherwise({redirectTo: '/connect'});
}]);

I want a function that can be common to HomeCtrl, AdminCtrland MainAppCtrl.

我想要一个可以对HomeCtrl,AdminCtrl和通用的函数MainAppCtrl

How should I do it in AngularJS?

我应该如何在 AngularJS 中做到这一点?

回答by ganaraj

The way to define common code in angular is through Services.

在 angular 中定义公共代码的方法是通过服务。

You would define a new service like so :

您可以像这样定义一个新服务:

.factory('CommonCode', function ($window) {
        var root = {};
        root.show = function(msg){
            $window.alert(msg);
        };
        return root;
    });

In your controller you would inject this service..like so

在您的控制器中,您将注入此服务..像这样

function MainAppCtrl($scope,CommonCode)
{
     $scope.alerter = CommonCode;
     $scope.alerter.show("Hello World");
}

Just include CommonCode as an argument to your controller function.. Angular will take care of injecting it for you ( Read on Dependancy Injection ..to understand what is happening here. )

只需将 CommonCode 作为参数包含在您的控制器函数中。Angular 将负责为您注入它(阅读依赖注入 ..以了解这里发生的事情。)

回答by Mistalis

Just to update previous answer (which only define what factoryis), there are 3 ways to inject dependencies(define common code) in AngularJS:

只是为了更新之前的答案(只定义了什么factory),有 3 种方法可以在 AngularJS 中注入依赖项(定义公共代码):

  • Providers
  • Factories
  • Services
  • 供应商
  • 工厂
  • 服务

I will not talk much about provider because it is a more laborious method for dependency injection. However, this pageexplains very well how they work.

我不会过多谈论 provider,因为它是一种更费力的依赖注入方法。然而,这个页面很好地解释了它们是如何工作的。



Technically, serviceand factoryare used for the same thing. It turns out, a service is a constructor function whereas a factory is not.

从技术上讲,服务工厂用于同一件事。事实证明,服务是构造函数,而工厂不是。

From this post:

这篇文章

module.service( 'serviceName', function );

When declaring serviceNameas an injectable argument you will be provided with an instance of the function.

当声明serviceName为可注入参数时,您将获得函数的一个实例

module.factory( 'factoryName', function );

When declaring factoryNameas an injectable argument you will be provided with the value that is returned by invoking the functionreference passed to module.factory.

当声明factoryName为可注入参数时,您将获得通过调用传递给 module.factory的函数引用返回的值



You can use the one you prefer and obtain the same result.

您可以使用您喜欢的方法并获得相同的结果

Here is two codes doing exactly the same thing through servicefirst, and then factory:

这里有两个代码service首先完成完全相同的事情,然后factory

Service syntax

服务语法

app.service('MyService', function () {
  this.sayHello = function () {
    console.log('hello');
  };
});

Factory syntax

工厂语法

app.factory('MyService', function () {
  return {
    sayHello: function () {
      console.log('hello');
    }
  }
});