"use strict"; angular.module("vocabulary") .component("addCategory", { templateUrl: "/js/redesign-angular/categories/add-category.html", controller: "AddCategory", bindings: { parentCategoryId: '<', onAddCategory: '<' } }) .controller("AddCategory", ["categoryService", "categoryValidationService", function(categoryService, categoryValidationService) { var ctrl = this; ctrl.newCategoryName = ""; ctrl.attemptCategoryCreation = function () { categoryValidationService.validateCategoryUpdate(ctrl.newCategoryName) // todo - this validation step should take place in the service .then(createCategory) .then(ctrl.onAddCategory) .then(clearInputField) .catch(setErrors); }; function createCategory() { return categoryService.createCategory(ctrl.newCategoryName, ctrl.parentCategoryId); } function clearInputField() { ctrl.newCategoryName = ""; ctrl.categoryForm.title.$setPristine(); } ctrl.resetDupe = function () { ctrl.categoryForm.title.$setValidity("dupe", true); }; ctrl.invalidField = function (field) { return field.$invalid && field.$dirty; }; ctrl.onEnter = function(keyEvent){ if(keyEvent.which === 13){ ctrl.attemptCategoryCreation(); } }; function setErrors(errors) { ctrl.categoryForm.title.$setDirty(); if (errors.duplicate) { ctrl.categoryForm.title.$setValidity("dupe", false); } } }]);