I am currently developing an AngularJS directive in TypeScript for form validation. I am trying to understand how to utilize the directive's controller and inherit the form controller within the directive's link function.
Thank you in advance!
module app.infrastructure.components.forms {
'use strict';
interface MyIFormController extends ng.IFormController {
$name: string;
}
interface IMskFormInputController {
setupDom: (element: any) => string;
addMessages: (form: ng.IFormController, element: ng.IAugmentedJQuery, name: string, scope: ng.IScope) => void;
updaterFor: (element: ng.IAugmentedJQuery) => any;
watcherFor: (form: ng.IFormController, name: string) => any;
}
class MskFormInputController implements IMskFormInputController {
static $inject = ['$compile'];
constructor(private $compile: ng.ICompileService) {
}
setupDom(element: any): string {
var name = null;
var input = element.querySelector("input, textarea, select, ui-select");
if (input !== undefined && input) {
name = input.getAttribute("name");
}
return name;
}
addMessages(form: any, element: ng.IAugmentedJQuery, name: string, scope: ng.IScope): void {
var messages = "<div class='help-block' ng-messages='" + form.$name + "." + name + ".$error" + "'>" +
"<div ng-messages-include='/app/infrastructure/directives/forms/messages.html'></div>" +
"</div>";
element.append(this.$compile(messages)(scope));
}
updaterFor(element: ng.IAugmentedJQuery): any {
return function (hasError) {
if (hasError) {
element.addClass("has-error");
}
else {
element.removeClass("has-error");
}
}
}
watcherFor(form: ng.IFormController, name: string): any {
return function () {
if (name && form[name]) {
return form[name].$invalid;
}
};
}
}
class MskFormInput implements ng.IDirective {
constructor() { }
static factory(): ng.IDirective {
return new MskFormInput;
}
controller = MskFormInputController;
controllerAs = 'mskFormInputController';
restrict = 'A';
require = ['^form'];
scope = {};
link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any): void {
//var name = form.setupDom(element[0]);
//this.controller.addMessages(form[0], element, name, scope);
//scope.$watch(this.controller.watcherFor(form[0], name), this.controller.updaterFor(element));
}
}
angular
.module('app.infrastructure.components.forms.mskFormInputDrtvmdl')
.directive('mskFormInput', MskFormInput.factory);
}