【发布时间】:2016-03-18 12:21:48
【问题描述】:
我是 AngularJS 的新手,我正在学习它的教程。我对在 Angular 中使用 factory 有疑问。
我知道工厂是一种用于根据请求创建对象的模式。
所以在示例中有如下代码:
// 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
});
这是与 factoryController 控制器相关联的代码,位于 HTML 页面内:
<div ng-controller="factoryController">
{{ courseName }}
</div>
所以我很清楚:
factoryController 使用 courseFactory 工厂,因为它是被注入的
-
当我打开页面时发生的第一件事是显示一条警告消息,因为它被称为:
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。
它究竟是如何工作的?为什么我不给工厂打电话? (或类似的东西)
【问题讨论】:
-
我建议阅读这个问题的答案stackoverflow.com/a/28262966/2435473
标签: javascript angularjs json javascript-framework angularjs-factory