Search code examples
cssangular-directive

CSS Style Positioning Issue


I have created one AngularJs directive to clear the input field. I want the "close" icon to be placed inside the respective input element. But its going out of input field.

Here is the plnkr - https://plnkr.co/edit/WHjRviyuYfFVfg2TnVUP?p=preview

Note: Please check the plnkr preview by resizing it.


Solution

  • var app = angular.module("myApp", []);
    
    app.controller("MyController", function($scope) {
        $scope.fname = "Hello!!"
        $scope.lname = "World";
     })
    .directive('clearField', function($compile) {
    	return {
    	  restrict: 'A',
    	  scope: {
    	    model: '=ngModel'
    	  },
    	  link: function(scope, element, attr) {
    	    // Add wrapper to the element
    	    scope.model = (scope.model == undefined) ? "" : scope.model;
    
    	    element.wrap('<span class="wrapper"></span>')
    	    .addClass('pr14')
    	    .after('<span class="clear">×</span>');
    
    	    var clearInputElement = angular.element(element.next());
    
    	    clearInputElement.bind('click', function() {
    	      scope.$apply(scope.model = "");
    	    });
    
    	    scope.$watch('model', function() {
    	      if (scope.model.length > 0) {
    	        clearInputElement.css("visibility", "visible");
    	      } else {
    	        clearInputElement.css("visibility", "hidden");
    	      }
    	    });
    	  }
    	}
    });
    .wrapper {
      position: relative;
      display: inline-block
    }
    
    .pr14 {
      padding-right: 17px;
    }
    
    .clear {
      position: absolute;
      right: 7px;
      color: grey;
      font-size: 17px;
    }
    
    .clear:hover {
      cursor: pointer;
      color: blue;
    }
    <!DOCTYPE html>
    <html lang="en" ng-app="myApp">
    
    <head>
      <meta charset="UTF-8" />
      <title>Document</title>
      <script data-require="[email protected]" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
      <script src="script.js"></script>
      <link rel="stylesheet" href="style.css">
    </head>
    
    <body ng-controller="MyController">
      <label>Name: </label>
      <input type="text" ng-model="fname" clear-field>
      <textarea  ng-model="lname" id="" cols="30" rows="10" clear-field></textarea>
    </body>
    
    </html>