AngularJS 应用程序组件(模块、工厂、控制器)定义究竟是如何工作的?

How exactly works the AngularJS application component (module, factory, controller) definition?

我绝对是 AngularJS 的新手,也是 JavaScript 的新手,我对教程中显示的这个示例有以下疑问:

// Creates values or objects on demand
angular.module("myApp")     // Get the "myApp" module created into the root.js file (into this module is injected the "serviceModule" service
.value("testValue", "AngularJS Udemy")

// Define a factory named "courseFactory" in which is injected the testValue
.factory("courseFactory", function(testValue) {
    // The factory create a "courseFactory" JSON object;
    var courseFactory = {
            'courseName': testValue,    // Injected value
            'author': 'Tuna Tore',
             getCourse: function(){     // A function is a valid field of a JSON object
             alert('Course: ' + this.courseName);   // Also the call of another function
            }
          };    
    return courseFactory;       // Return the created JSON object
})

// Controller named "factoryController" in which is injected the $scope service and the "courseFactory" factory:
.controller("factoryController", function($scope, courseFactory) {
    alert(courseFactory.courseName);        // When the view is shown first show a popupr retrieving the courseName form the factory
    $scope.courseName = courseFactory.courseName;
    console.log(courseFactory.courseName);
    courseFactory.getCourse();  // Cause the second alert message
});

我很清楚它做了什么:它创建了一个代表我的应用程序的 angular 模块,它被命名为 myApp。然后定义一个值,一个工厂(即 return 一个 courseFactory JSON 对象),最后是一个控制器,其中注入了先前的工厂。

我觉得不太清楚的是这些"components"的声明语法。

所以,在我看来,"syntax" 是这样的:

angular.module("myApp").value(VALUE DECLARATION).factory("courseFactory", function(testValue) { RETURN THE JSON OBJECT IMPLEMENTING THE FACTORY }).controller("factoryController", function($scope, courseFactory) { IMPLEMENT THE CONTROLLER });

所以我的疑问是:为什么所有 "components"(value 声明、factory 实现和 controller 实现)在 "concatentaion chain" 中定义,其中“.”符号将这些组件添加到链中?

这个“.”到底是什么意思? ?

我认为它向对象或类似的东西添加了一个字段,但我觉得很奇怪。

所以首先是 angular 对象(它是一个对象还是什么?)在其上添加了 模块("myApp") "component"(这似乎合乎逻辑,因为我正在向 Angular 添加一个模块)。

然后添加一个作为这个模块的属性。这似乎也有道理,因为我正在向特定的 模块 .

添加 value

但是为什么要添加一个 factory 作为这个 value 的字段然后 controller 添加为此 factory?

的字段

我想我错过了什么。

我错过了什么? AngularJS "component" 定义的工作原理如何?

以下:

angular.module("myApp")

将return表示模块的对象。

您可以通过以下方式进行检查:

console.log(angular.module("myApp"));

你会看到这个对象有一堆方法,例如valuecontrollerfactory

这解释了为什么您可以执行以下操作:

angular.module("myApp").value("testValue", "AngularJS Udemy");

诀窍在于值方法还 return 模块对象,因此您可以继续链:

angular.module("myApp").value("testValue", "AngularJS Udemy").factory(...)

模块对象上的其他方法也是如此。

有方法 return 像这样连接主要对象是允许这种链接的常用技术。

你可以这样读:

var myModule;

myModule = angular.module('myApp'); // Returns the module

myModule = myModule.value(...); // Registers a value and returns the module

myModule = myModule.factory(...); // Registers a factory and returns the module