I'm writing a todo app as a test. Having never done Ionic nor Angular apps before, I am not sure if I am following best practices here.
What I have done is try to keep my controllers thin by placing all persistant logic in the model (service?). And instead of hard coding links in the view, I am calling a function in the controller.
Are there any other things I should or shouldn't be doing?
// controllers
angular.module('starter.controllers', [])
.controller('TodosCtrl', function($scope, Todos, $state) {
$scope.todos = Todos.all();
$scope.data = {
showDelete: false
};
$scope.add = function() {
$state.go('tab.add');
};
$scope.remove = function(todo) {
Todos.remove(todo);
};
})
.controller('TodoDetailCtrl', function($scope, $stateParams, Todos, $state) {
$scope.todo = Todos.get($stateParams.todoId);
$scope.remove = function(todo) {
Todos.remove(todo);
$state.go('tab.todos');
};
})
.controller('TodoAddCtrl', function ($scope, $state, Todos) {
$scope.content = {};
$scope.add = function() {
var todo = $scope.content.name;
if(todo) {
$scope.content.name = '';
Todos.add({
id: Todos.all().length + 1,
name: todo
});
$state.go('tab.todos');
}
};
})
.controller('AccountCtrl', function($scope) {
// unused for now
$scope.settings = {
enableServer: true
};
})
// services
angular.module('starter.services', ['ngStorage'])
.factory ('StorageService', function ($localStorage) {
$localStorage = $localStorage.$default({
todos: []
});
var _getAll = function () {
return $localStorage.todos;
};
var _add = function (todo) {
$localStorage.todos.push(todo);
}
var _remove = function (todo) {
$localStorage.todos.splice($localStorage.todos.indexOf(todo), 1);
}
return {
getAll: _getAll,
add: _add,
remove: _remove
};
})
.factory('Todos', function(StorageService) {
// Might use a resource here that returns a JSON array
var todos = StorageService.getAll();
return {
all: function() {
return todos;
},
remove: function(todo) {
StorageService.remove(todo);
},
add: function(todo) {
StorageService.add(todo);
},
get: function(todoId) {
for (var i = 0; i < todos.length; i++) {
if (todos[i].id === parseInt(todoId)) {
return todos[i];
}
}
return null;
}
};
})