I am an angular/ionic noob and need an ELI5 on how to use the service service and factory service. I am also terrible at interpreting the docs.
I have an array $scope.todos
and would like a method to create a new todo. I am currently using this code here:
.factory('TodoItem', function () {
return function TodoItem(title) { //more arguments may be added later
this.title = title;
}
})
and when I want to create a new TodoItem
I will use this
new TodoItem("This is a thing to do");
Q1: Is this the 'correct' way to use the factory?
Now, on to the service. My code is broken (below) and I have no idea how to fix it, presumably because I do not understand the service at all. Q2: Would you be able to do an ELI5 on how this is supposed to work?
.service('addTodoItem', function () {
function ($scope, todoItem) {
if (!$scope.todos)
$scope.todos = [todoItem];
else
$scope.todos.push(todoItem);
}
})
I (attempt to) use this code to add the new TodoItem
to the array.
$addTodoItem($scope, new TodoItem('Hello'));
Edit: I have tried watching a YouTube tutorial and come up with this code here.
.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;
}
})
And I use this to add new TodoItems
todoItems.add(createTodoItem("This is a test todo"));