这个AngularJS工厂的例子究竟如何?有些疑惑

And*_*ili 5 javascript json javascript-framework angularjs angularjs-factory

我是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
});
Run Code Online (Sandbox Code Playgroud)

这是与此factoryController控制器关联的代码,位于HTML页面内:

<div  ng-controller="factoryController"> 
    {{ courseName }} 
</div> 
Run Code Online (Sandbox Code Playgroud)

所以我很清楚:

  • 由于被注入,factoryController使用courseFactory工厂

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

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

这是我的第一个怀疑.我认为工厂的定义是:

.factory("courseFactory", function(testValue)
Run Code Online (Sandbox Code Playgroud)

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

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

$scope.courseName = courseFactory.courseName;
Run Code Online (Sandbox Code Playgroud)

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

它究竟如何运作?为什么我不在工厂打电话?(或类似的东西)

Pro*_*eek 2

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

您可能想阅读第一篇《工厂与服务》

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

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

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