gpt4 book ai didi

javascript - 这个 AngularJS 工厂示例究竟是如何工作的?一些疑惑

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:41 24 4
gpt4 key购买 nike

我是 AngularJS 的新手,我正在学习教程。我对 Angular 中工厂的使用有疑问。

我知道工厂是一种用于根据请求创建对象的模式。

所以在例子中有如下代码:

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

这是在 HTML 页面内与此 factoryController Controller 关联的代码:

<div  ng-controller="factoryController"> 
{{ courseName }}
</div>

所以我很清楚:

  • factoryController 使用 courseFactory 工厂,因为它被注入(inject)了

  • 当我打开页面时发生的第一件事是显示一条警告消息,因为它被称为:

    alert(courseFactory.courseName);
  • 然后将 courseFactory 的 **courseName 字段的值放入 $scope.courseName 属性(在 $scope 对象内) JSON 对象)。

这是我的第一个疑问。我知道工厂定义为:

.factory("courseFactory", function(testValue)

我认为这意味着(如果我做错了断言请纠正我)我的工厂被命名为 courseFactory 并且基本上是一个返回 courseFactory JSON 对象的函数。

所以这让我有些困惑(我来自 Java),因为在 Java 中我调用工厂类并获得工厂创建的对象的实例。但在这种情况下,在我看来,这样做:

$scope.courseName = courseFactory.courseName;

在我看来,courseName 是由 courseFactory JSON 对象直接检索的,我没有使用 courseFactory

具体是如何运作的?为什么我不给工厂打电话? (或类似的东西)

最佳答案

为了简化事情有两种已知的方法来创建在所有状态中可用的函数(和方法)(将其视为在全局范围内创建函数),它们是工厂和服务。

您可能想先阅读此内容 Factory vs Service

it seems to me that the courseName is retrieved directly by the courseFactory JSON object and I am not using the courseFactory.

实际上这是部分正确的,因为 Angular 使用 DI 概念(依赖注入(inject)),你将不得不注入(inject)你的工厂(它默认返回一个对象,以及相应的函数作为属性),如果你不这样做的话;您将无法使用您的工厂对象方法。

Angular 并不神奇,只是大多数人没有意识到 JavaScript 的最基本概念,特别是来自不同编程环境(如 C#、C++ 或 Java)的开发人员

关于javascript - 这个 AngularJS 工厂示例究竟是如何工作的?一些疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com