了解 Angular.js 控制器参数 [英] Understanding Angular.js controller parameters

查看:20
本文介绍了了解 Angular.js 控制器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 Angular.js,我一直在研究 项目Angular 主页上的连接后端"示例中的 .js.

I'm just starting to learn Angular.js and I've been looking at the project.js in the "Wire up a Backend" example on the Angular home page.

我对控制器函数中的参数感到困惑:

I'm confused about the parameters in the controller functions:

function ListCtrl($scope, Projects) {
  ... 
}   

function CreateCtrl($scope, $location, $timeout, Projects) {
  ... 
}

function EditCtrl($scope, $location, $routeParams, angularFire, fbURL) {
   angularFire(fbURL + $routeParams.projectId, $scope, 'remote', {}).
   then(function() {
     ...
   });
}  

在routeProvider中调用了这些控制器函数,但没有给出任何参数.

These controller functions are called in the routeProvider, but none of the parameters are given.

$routeProvider.
  when('/', {controller:ListCtrl, templateUrl:'list.html'}).
  when('/edit/:projectId', {controller:EditCtrl, templateUrl:'detail.html'}).
  when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
  otherwise({redirectTo:'/'});
});

到目前为止我能找到的唯一可能解释发生了什么的是"Injecting Services Into控制器",解释了$location$timeout,但不解释参数方法angularFirefbURL.

The only thing I could find so far that possibly explains what's going is "Injecting Services Into Controllers", which explains $location, $timeout, but not parameters method angularFire and fbURL.

我的具体问题是:

  1. 控制器参数可以是什么?

  1. What can the controller parameters be?

使用参数调用的控制器函数在哪里?或者参数没有被调用而只是与控制器相关联的东西,其中关联发生了很多 Angular.js 魔法(如果是这样,我可以在 github 上看到源代码)?

Where are the controller functions called with their parameters? Or the parameters are not called but are just stuff associated with the controller where the association occurs with lots of Angular.js magic (if so, can I see the source code on github)?

angularFire 在哪里定义?

参数中的fbURL是如何链接到的:

How is the fbURL in the parameter linked to:

angular.module('project', ['firebase']).
    value('fbURL', 'https://angularjs-projects.firebaseio.com/').
    factory ...

  • 有没有可以看到所有服务的地方,例如$location$timeout,Angular.js 提供的?(我试图找到列表但失败了.)

  • Is there a place where I can see all the services, e.g. $location and $timeout, that Angular.js provides? (I tried to find the list but failed.)

    推荐答案

    • 控制器参数可以是什么?

      控制器参数是依赖项,由AngularJS注入器服务注入.他们可以是任何东西.但它们通常是将在控制器内部使用的服务.

      The controller parameters are dependencies, which are injected by AngularJS injector service. They can be anything. But they are usually the services that will be used inside the controller.

      使用参数调用的控制器函数在哪里?

      控制器,以及指令、过滤器、服务和 AngularJS 中的许多其他东西都是函数.但是框架管理了很多何时如何调用这些函数.

      Controllers, as well as directives, filters, services and so many other things in AngularJS are functions. But the framework manages a lot of when and how these functions are called.

      你所说的关联的东西有一个名字:依赖,如上所述.你所说的魔法是AngularJS的依赖注入机制.

      What you call stuff associated has a name: dependency, as mentioned above. What you call magic is AngularJS dependency injection mechanism in action.

      当注入器调用这些函数(控制器和其他)时,它会读取参数名称(例如:$scope$httpangularFire) 并搜索具有该名称的注册服务,然后在调用函数时将其作为参数提供.

      When these functions (controllers and others) are called by the injector, it reads the parameters names (for example: $scope or $http or angularFire) and searches for a registered service with that name, which is then provided as the parameter when the function is called.

      很简单.您有多种方法可以将您的依赖项"(由注入器管理的参数)指示给注入器.

      It is simple. You have several ways to instruct about your "dependencies" (parameters managed by the injector) to the injector.

      当您简单地将函数声明为 function myCtrl($scope) {} 时,注入器将能够从参数名称中找到 $scope 服务.但是如果您缩小 JavaScript 代码,注入器将无法再找到该服务,因为参数名称将被修改为更小的字符串,例如a"或x".为了避免这个问题,可以使用数组表示法指定要注入的服务名称.在这种情况下,您可以像这样声明您的函数:myCtrl = ['$scope', function($scope) {}]

      When you simply declare your function as function myCtrl($scope) {}, the injector will be able to find the $scope service from the parameter name. But if you minify the JavaScript code, the injector will not be able to find the service anymore, because the parameter name will be modified to a smaller string, like "a" or "x". To avoid this problem, it is possible to specify the service name to be injected using the array notation. In this case, you would declare your function like this: myCtrl = ['$scope', function($scope) {}]

      您会在 AngularJS 世界中看到很多数组表示法的用法.现在你开始理解它.您甚至可以注入 $scopeangularFire 并在您的函数中将它们与 其他名称 一起使用(不建议更改名称strong> - 这个例子是为了学习目的):['$scope', 'angularFire', function(skop, af) {}] - 这样,在函数内部你可以使用 $scope作为skop"和angularFire作为af".数组中服务的顺序与参数的顺序相匹配.

      You will see a lot of array notation usage in AngularJS world. Now you start to understand it. You could even inject $scope and angularFire and use them with other names in your function (changing the name is not recommended - this example here comes for learning purposes): ['$scope', 'angularFire', function(skop, af) {}] - this way, inside the function you can use $scope as "skop" and angularFire as "af". The order of the services in the array matches the order of the parameters.

      另一个例子:

      var myController = ['$scope', '$resource', '$timeout',
          function($scope, $resource, $timeout) {
              // this controller uses $scope, $resource and $timeout
              // the parameters are the dependencies to be injected
              // by AngularJS dependency injection mechanism
          }
      ];
      

      • angularFire 在哪里定义?

        firebase 模块中.

        正如您现在已经知道的,注入器会注入任何东西,只要它在其记录中注册了事物"名称.如果有具有该名称的服务",他就可以提供.

        As you already know now, the injector will inject anything as long as it has that "thing" name registered and available on its records. If there is a "service" with that name, he is able to provide it.

        然后,如何构建这个name =>注入器使用的东西列表?

        How, then, is built this name => stuff list which the injector uses?

        模块就是答案.模块 只不过是一个 name =>; 的列表.东西.它位于模块中,您可以在其中注册服务、工厂、过滤器、指令等.

        Module is the answer. A module is little more than a list of name => stuff. It is in a module where you register services, factories, filters, directives, and more.

        仔细查看官方文档中的模块方法...几乎所有这些方法都作为参数接收:name 和一些stuff"(其中stuff"几乎总是一个函数,定义控制器、工厂或指令).所有这些东西"都将通过他们指定的名称成为可注射.

        Look carefully at the Module methods at the official documentation... almost all of them receive as parameters: name and some "stuff" (where "stuff" is almost always a function, defining either a controller, or a factory, or a directive). It is all this "stuff" that will become injectable through their specified name.

        $timeout"、$http"等 AngularJS 服务默认可用,因为框架已经加载了 ng 模块.

        AngularJS services like "$timeout", "$http" and others are available by default because the ng module is already loaded by the framework.

        对于其他服务,您需要加载/需要模块.这就是您使用 ngRouterfirebase 等所做的事情...通过加载 模块,其注册的内容可用于注入您的模块/应用中.

        For additional services, you need to load/require the module. That's what you do with ngRouter, firebase, etc... By loading the module, its registered stuff are available for injection in your module/app.

        让我们看一个分步示例:

        Let's see a step-by-step example:

        // An empty module:
        var module = angular.module('myModule', []);
        
        // Now, adding an "injectable" constant: 
        module.constant('niceStuff', { blip: 'blop', blup: 307 });
        
        // We could add a service:
        module.service('entityManager', ['$http', function($http){  }]);
        
        // and so on... if I wanted to use "$resource" instead of "$http"
        // in the entityManager service above...
        // ...I would need to require the ngResource when creating the module above,
        // like this: var module = angular.module('myModule', ['ngResource']);
        // because "$resource" is not available by default
        
        // NOW, anywhere else, since the code above already ran
        // I can use those NAMES as dependencies like this:
        
        // We are creating another module now:
        var koolModule = angular.module('km', ['myModule']);
        // Note that I am requiring the previous module through its registered name
        
        // Now, anything I've declared in that module
        // - just like "ng" (by default) and "firebase" (required) does -
        // is available for "injection"!!!
        
        koolModule.controller('koolController',
            ['niceStuff', 'entityManager', function(niceStuff, entityManager) {
                console.log(niceStuff.blip);      // 'blop'
                console.log(niceStuff.blup + 10); // 317
            }]
        );
        

        这就是 firebase 的东西,比如 angularFire,变得可用的方式!我们做了什么?首先,我们创建了myModule",并向其注册了 NAMED 内容.后来,我们需要为我们的koolModule"提供myModule"——而那些 NAMES 已经在注入器中可用 name =>;东西列表.

        This is how firebase stuff, like angularFire, becomes available! What have we done? First, we created the "myModule", and registered NAMED stuff to it. Later, we required the "myModule" for our "koolModule" - and those NAMES were already available in the injector name => stuff list.

        • 参数中的fbURL是如何链接的

        正如我们刚刚看到的,大多数模块方法只是注册事物 - 为事物赋予名称,以便它们可以注入和/或稍后通过这些名称使用.

        As we've just seen, most module methods are merely registering things - giving names to things so they can be injected and/or used through these names later.

        module.value('fbURL', 'https://angularjs-projects.firebaseio.com/') 被调用时,fbURL(和指定的值) 注册到 name =>东西 列表...在这种情况下,名称是fbURL",值/东西是 URL 字符串 - 但它可以是任何东西!

        When module.value('fbURL', 'https://angularjs-projects.firebaseio.com/') is called, fbURL (and the specified value) is registered into the name => stuff list... in this case, the name is "fbURL", and the value/stuff is the URL string - but it could be anything!

        有没有可以看到所有服务的地方,例如$location 和 $timeout,Angular.js 提供的?

        是的,API 参考:http://docs.angularjs.org/api/

        注意左侧导航的组织方式...模块!首先是 ng 模块,包含大量指令、服务、过滤器等.然后是其他模块(ngRoute、ngResource、ngMock 等),每个模块都包含自己的服务,过滤器或指令...

        Pay attention at how the left-side navigation is organized... by modules! First, the ng module, with tons of directives, services, filters, etc. Then, below, the other modules (ngRoute, ngResource, ngMock, and so on), each one containing their own services, fitlers or directives...

        感谢您有机会分享这些想法.我喜欢写它们.

        Thanks for the opportunity of sharing these thoughts. I enjoyed writing them.

        这篇关于了解 Angular.js 控制器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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