I'd like to create a ToDo app in AngularJS that uses nested ToDos. As part of this, I'd like the ability to indent or outdent a ToDo with a click (ultimately, it will react to a 'tab' or 'shift-tab' keypress). When indenting, the function should also indent any child ToDos. This is where I'm having trouble. I'm not sure how to implement a recursive function in a directive. If anyone has seen this done or could offer any help, i would appreciate it. I've created a working JSFiddle that indents a single ToDo but doesn't indent it's children. JS Fiddle is here https://jsfiddle.net/t1ba50k6/16/
Also, please offer any best practices on coding convention or to clean up the directive.
Thanks!
My HTML:
<ul id=Todos ng-app="app" ng-controller="todos">
<div ng-repeat='todo in model' ng-init="todoIndex = $index">
<todo-item content="todo"></todo-item>
</div>
My javascript:
var app = angular.module('app', []);
app.controller("todos", function ($scope) {
$scope.model = [{
"title": "Task item one",
"indentLevel": 1
}, {
"title": "Task item two",
"indentLevel": 2
}, {
"title": "Task item three",
"indentLevel": 2
}];
});
app.directive('todoItem', function ($compile) {
var getTemplate = function (content) {
var startStr = '';
var endStr = '';
if (content.indentLevel == 1) {
startStr = '<li class="todolist"><table><tr><td><div class="checkboxpadding"><img width="16" height="16" class="checkbox"></div></td><td><div ng-click="indent()">';
endStr = '</div></td></tr></table></li>';
return startStr + content.title + endStr;
} else if (content.indentLevel == 2) {
startStr = '<li class="todolist indent_2""><table><tr><td><div class="checkboxpadding"><img width="16" height="16" class="checkbox"></div></td><td><div ng-click="indent()">';
endStr = '</div></td></tr></table></li>';
return startStr + content.title + endStr;
}
};
var linker = function (scope, element, attrs) {
element.html(getTemplate(scope.content)).show();
$compile(element.contents())(scope);
scope.indent = function () {
var childElem = angular.element(element.children()[0]);
if (scope.content.indentLevel < 3) {
childElem.removeClass("indent_" + scope.content.indentLevel);
childElem.addClass("indent_" + (scope.content.indentLevel + 1));
scope.content.indentLevel++;
// update Database
// indent child nodes?
// for (var i=0; i < nodes; i++) { }
}
};
};
return {
restrict: "E",
link: linker,
scope: {
content: '='
}
};
});