AngularJS应用程序组件(模块、工厂、控制器)定义的确切工作方式

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

本文关键字:定义 方式 工作 控制器 组件 应用程序 模块 工厂 AngularJS      更新时间:2023-09-26

我是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
});

我很清楚它做了什么:它创建了一个角度模块来表示我的应用程序,并命名为myApp。然后定义一个值、一个工厂(返回courseFactoryJSON对象),最后定义一个控制器,在该控制器中注入前一个工厂。

我不清楚的是这些"组件"声明的语法。

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

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 });

因此,我的疑问是:为什么所有的"组件"(声明、工厂实现和控制器实施)都定义在"连接链"中,其中"."符号将这些组件添加到链中?

这个"."到底是什么意思?

我认为它为一个对象或类似的东西添加了一个字段,但这对我来说似乎很奇怪

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

然后添加一个作为该模块的属性。而且这似乎是有意义的,因为我正在向特定的模块添加一个

但是,为什么一个工厂被添加为该值的字段,然后控制器又被添加为这个的字段?

我想我错过了什么。

我错过了什么?AngularJS"组件"定义是如何实际工作的?

以下内容:

angular.module("myApp")

将返回表示模块的对象。

您可以通过以下操作进行检查:

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

您将看到该对象有一组方法,例如valuecontrollerfactory

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

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

诀窍是value方法还返回模块对象,这样你就可以继续这个链:

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

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

使用这样的方法返回主对象是允许这种链接的常见技术。

你可以这样读:

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