【发布时间】:2016-03-18 22:46:38
【问题描述】:
我在 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。然后定义一个值、一个工厂(返回一个 courseFactory JSON 对象),最后定义一个控制器,之前的工厂被注入其中。
认为我不清楚的是这些“组件”的声明语法。
所以,在我看来,“语法”是这样的:
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 });
所以我的疑问是:为什么定义了所有“组件”(value 声明、factory 实现和 controller 实现)在“连接链”中的“。”符号将这些组件添加到链中?
这个“.”到底是什么意思?
我认为它向对象或类似的东西添加了一个字段,但对我来说似乎很奇怪。
首先是 angular 对象(它是一个对象还是什么?),在其上添加了 module("myApp") “组件”(以及似乎合乎逻辑,因为我正在向 Angular 添加一个模块)。
然后添加一个值作为这个模块的属性。而且这似乎很有意义,因为我正在向特定 module 添加一个 value。
但是为什么然后一个 factory 作为这个 value 的字段添加,然后 controller 作为这个 的一个字段添加工厂?
我觉得我错过了什么。
我错过了什么? AngularJS“组件”定义是如何工作的?
【问题讨论】:
标签: javascript angularjs javascript-objects angularjs-controller angularjs-factory