Angular: Directive Testing for Input Validation

http://angularjs.org/

by sberube

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-controller="MyCtrl">{{name}}&lrm;&nbsp;{{test}}
    <form name="form" novalidate>
        <input name="test" ng-model="inputTest" ng-required="true" ng-maxlength="5" ng-minlength="3"></input>
        <br></br> <span>Input Error: {{form.test.$error}}</span>

        <br></br>
        <field-icon for="form.test" help-title="This is a helptip"></field-icon>
    </form>
</div>

CSS

.icon-field {
}
.icon-field .error {
    background-color: red;
}

JavaScript

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.test = 'Test';

    $scope.inputTest = "";
}


myApp.directive('fieldIcon', function () {
    return {
        restrict: 'E',
        template: '<i class="icon-field">?</i>',
        replace: true,
        require: '^form',
        scope: {
            for: "=for",
            helpTitle: "@"
        },
        link: function postLink($scope, $element, $attrs) {
            // Requires JQuery
            var form = $element.closest("form");
            var $input = $element.siblings("[name=" + $scope.for.$name + "]");
            
            var maxLength = $input.attr('ng-maxlength');
            var minLength = $input.attr('ng-minlength');
            var required = $input.attr('ng-required');          

            var unregister = $scope.$watchCollection('for.$error', function (newValue) {
                //window.alert('changed');
                if ($scope.for.$valid) {
                    $element.html($scope.helpTitle);
                } else {
                    if ($scope.for.$error.required) {
                        $element.html("Required Field");
                    } else if ($scope.for.$error.minlength) {
                        $element.html("Does not meet minimum length of " + minLength);
                    } else if ($scope.for.$error.maxlength) {
                           $element.html("Too Long");
                    }
                }
                //window.alert($scope.for.$valid);
            });
        }
    };
});