0

I am creating the custom directive for input validation. Here I checked the input length, if input length is zero, it will show the error and am not unable to if an input is filled with characters, I want to hide it.

Here is my Code :

app.directive("formValidate", function() {
  return {
    require: 'ngModel',
    template: '<p>Please Fill this Field</p>',
    link: function(scope, elem, attr) {

        scope.$watch(attr['ngModel'], function(value) {

            if (((value || '').toString()).length == 0) {
                var errorMessage = angular.element("<p class='error'>This field is requiured!</p>");
                errorMessage.insertAfter(elem);
                //$compile(errorMessage)(scope);
            } else {
                 // What to do??
            }
        })


   <input form-validate required md-no-asterisk ng-model="newEmployee.name" type="text" id="name" name="name">
code.cycling
  • 1,246
  • 2
  • 15
  • 33

1 Answers1

0

If you want to hide element using class then you can create a class with

display:none

property, and apply class using ng-class

But angular itself provides good directives called ng-show or ng-hide.

ng-show or ng-hide will render DOM element but will just hide on condition satisfied. If you use ng-if it will not even render DOM until and unless the condition is satisfied.

if (((value || '').toString()).length == 0) {
   $scope.hasError = true;
}else{
//do whatever 
}

in HTML just use

<p ng-show="hasError">Your Error Msg</p>

There are so many other methods can be used to do the same.