Aanchal Aanchal - 2 months ago 7
AngularJS Question

Clear input icon is not working properly in form which is having validations of angular js

I am trying to implement input clear icon in input textbox in my form . I am doing it through one directive. But its not working properly. Whenever I write something in input box , cross button doesn't show up untill and unless it is valid input for example when I type three characters in company name then only it shows up the cross button and not when characters are less than 3 or when the pattern is wrong.. I want that it should show everytime when I am writing any value in textbox. And when I click on cross button , it should clear the text and the required condition should be shown which is shown currently also when I am clicking cross. I am using below code for directive -

.directive('inputClearNoMaterial', function(){
return {
restrict: 'A',
compile: function (element, attrs) {
var color = attrs.inputClearNoMaterial;
var style = color ? "color:" + color + ";" : "";
var action = attrs.ngModel + " = ''";
element.after(
'<span class="animate-show"' +
'ng-show="' + attrs.ngModel + '" ng-click="' + action + '"' +
'style="position: absolute; margin: 3px 0px; cursor: pointer; ">' +
'<div style="' + style + '">x</div>' +
'</span>');
}
};
});


Can anyone help me in this? Also cross button should be shown inside textbox as currently its outside the box. I have created a plunker here-
https://plnkr.co/edit/4sXB3S9HAuvszlZdimIU?p=preview

Answer

Here is the working link

Modify your directive code as per below

 .directive('inputClearNoMaterial', ['$compile','$timeout',function($compile,$timeout){
    return {
    restrict: 'A',
    require: 'ngModel',
    scope: {},
    link: function(scope, el, attrs, ctrl) {

     var color=attrs.inputClearNoMaterial;
       var style = color ? "color:" + color + ";" : "";

      var template = $compile('<i ng-show="enabled" ng-mousedown="clear()" style="' + style + '" class="fa fa-times-circle"></i>')(scope);
      el.after(template);

      scope.clear = function() {
        ctrl.$setViewValue(null);
        ctrl.$render();
        $timeout(function() {
            el[0].focus();
        }, 0, false);
      };

      el.bind('input focus', function() {
        scope.enabled = !ctrl.$isEmpty(el.val());
        scope.$apply();
      })
      .bind('blur', function() {
        scope.enabled = false;
        scope.$apply();
      });
    }
  };
        }]);