Gangadhar Jannu Gangadhar Jannu - 4 months ago 59
AngularJS Question

Clear icon inside input text box angular way

I have been trying to create a clear icon inside text box.

My code snippet will do below things:


  1. initially clear icon is hidden

  2. when we type anything in text box, if the text box is in focus and the text box has some value in it then the clear icon will be displayed.

  3. If anyone click on clear icon, it will clear the corresponding text box content.



In simple I want to create a replica of clear icon that is displayed in webkit browsers search box.

When I click on clear icon it will clear the corresponding text box.
But that doesn't happening

Could anyone figure out what I missed?

HTML

<div ng-controller="clearCtrl">
<div>
<input type="text" ng-model="userModal" ng-keyup="clearIcon(true)" ng-blur="clearIcon(false)"/>
<span ng-click="clearInput()" ng-class="clearIconVar?'displayClear':'hideClear'" >x</span>
</div>
</div>


CSS

.displayClear{
cursor:pointer;
color:#38468F;
position:relative;
right:21px;
}
.hideClear{
display:none;
}


angular Javascript

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

.controller('clearCtrl', function($scope) {
$scope.clearIconVar=false;
$scope.clearIcon = function(param){
$scope.clearIconVar=param;
};
$scope.hi="hi";
$scope.clearInput=function(){
alert("hi");
};
});


Here is the jsbin demo

How can one do like this?

I am happy to accept any suggestions on this?

Answer

Hi all after a while I am able to achieve what I want :)

So here is the code to achieve what I want

HTML:

<div ng-controller="MyCtrl">
  <input type="text" ng-model="userId" ng-change="clearIconToggle('userId')">
  <span ng-show="userIdClear" ng-click="clearText('userId')">X</span>

  <input type="text" ng-model="passwd" ng-change="clearIconToggle('passwd')">
  <span ng-show="passwdClear" ng-click="clearText('passwd')">X</span>

  <input type="text" ng-model="dob" ng-change="clearIconToggle('dob')">
  <span ng-show="dobClear" ng-click="clearText('dob')">X</span>

</div>

JS:

var app=angular.module("myApp",[]);
app.controller("MyCtrl",["$scope",function($scope){
  $scope.userIdClear="false";
  $scope.passwdClear="false";
  $scope.dobClear="false";
  $scope.clearIconToggle=function(param){

    if($scope[param].length)
      $scope[param+'Clear']=true;
    else
      $scope[param+'Clear']=false;
  };
  $scope.clearText=function(param){
    $scope[param]='';
    $scope.clearIconToggle(param);
  };

}]);

You can find the working demo here