I am starting an angular app and I was wondering if I am on the right track with this. I worked on my last angular app when I was just a youngun who didn't understand the important of designing the code properly. I failed so hard at keeping the code clean and maintainable, mostly due to not understanding directives or services.
I am wondering if there is a better structure to my error handling in the below code. Is that too much logic in the controller functions? All I am doing is allowing the adding of items to a list, but not allowing them to be added or removed if the list length is < 5 or > 1 respectively. If there are other problems besides the controller logic, please let me know.
var toDo = angular.module('toDo',[]);
toDo.factory('listEdit', function() {
return {
add: function(list, item) {
list.push(item);
return list;
},
remove: function(list, index) {
list.splice(index, 1);
return list;
},
count: function(list) {
return list.length;
}
}
});
//Error handling methods
toDo.controller('main', ['$scope', 'listEdit', function($scope, listEdit) {
$scope.list = [];
$scope.addToList = function() {
list_length = listEdit.count($scope.list);
if(list_length < 5) {
$scope.list = listEdit.add($scope.list, $scope.todo);
} else {
alert('Too many list items');
}
}
$scope.remove = function(index) {
list_length = listEdit.count($scope.list);
if(list_length > 1) {
$scope.list = listEdit.remove($scope.list, index);
} else {
alert("You can't delete this last item");
}
}
}]);
HTML
<body ng-controller="main">
<input type="text" ng-model="todo">
<button ng-click="addToList()">Add to List</button>
<div ng-repeat="todo in list track by $index">
<span ng-click="remove($index)">{{todo}}</span>
</div>
</body>