Angularjs 什么是';正确的方法';添加到$scope.someArray的上下文中的服务和工厂
我是一个棱角分明/爱奥尼亚式的noob,需要一份关于如何使用服务和工厂服务的ELI5。我在解释文件方面也很糟糕 我有一个数组Angularjs 什么是';正确的方法';添加到$scope.someArray的上下文中的服务和工厂,angularjs,service,factory,Angularjs,Service,Factory,我是一个棱角分明/爱奥尼亚式的noob,需要一份关于如何使用服务和工厂服务的ELI5。我在解释文件方面也很糟糕 我有一个数组$scope.todo,想要一个方法来创建一个新的todo。我目前正在这里使用此代码: .factory('TodoItem', function () { return function TodoItem(title) { //more arguments may be added later this.title = title; } }
$scope.todo
,想要一个方法来创建一个新的todo。我目前正在这里使用此代码:
.factory('TodoItem', function () {
return function TodoItem(title) { //more arguments may be added later
this.title = title;
}
})
当我想创建一个新的TodoItem
时,我会使用这个
new TodoItem("This is a thing to do");
问题1:这是使用工厂的“正确”方式吗
现在,转到服务。我的代码坏了(如下),我不知道如何修复它,大概是因为我根本不了解服务。问题2:你能做一个关于这应该如何工作的ELI5吗
.service('addTodoItem', function () {
function ($scope, todoItem) {
if (!$scope.todos)
$scope.todos = [todoItem];
else
$scope.todos.push(todoItem);
}
})
我(尝试)使用此代码将新的TodoItem
添加到数组中
$addTodoItem($scope, new TodoItem('Hello'));
编辑:我试着看了一个YouTube教程,在这里找到了这个代码。
.factory('createTodoItem', function () {
console.log("createTodoItem factory called")
function TodoItem(title) {
//Constructor
this.title = title;
}
function createTodoItem (title) {
var newItem = new TodoItem(title);
return newItem;
}
return createTodoItem;
})
.provider('todoItems', function () {
this.$get = function () {//the get method is called once
console.log("todoItems get called")
var todoItems = {
items:[],
add:function (todo) {
console.log("todoItems add was called", this.items);
todoItems.items.push(todo);
console.log("todoItems now is:", todoItems.items)
}
};
return todoItems;
}
})
我用它来添加新的TodoItems
todoItems.add(createTodoItem("This is a test todo"));
在angular services和Factory中,是特定类型的提供商。据我所知,它们旨在重用应用程序不同控制器中的代码,因此,只有在2个或更多不同控制器中使用函数时,才需要它们。在声明它们之后,您需要将它们作为控制器的依赖项注入 您可能应该将函数声明为作用域的变量,然后使用它,例如:
$scope.addTodoItem = function (item) {
$scope.todos.push(item);
};
这里出了很多问题。建议你看一些角度教程。我试着看了一个不同的YT教程,并提出了一些新的代码,如文章所示。你能看到现在有多少事情是错的吗PYou可能不需要
提供者
,但工厂现在更明智了。如果您返回一个对象,可以为factory添加更多功能。谢谢。你们能进一步解释为什么我不需要那个provider吗?若你们需要它在应用程序的配置阶段是可配置的,通常创建provider。