Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive input width resize by keyup

I created a directive in order to make a input that has width automatically resized when keyup (like Google Contacts). However it seems not to be ok, because the width of each characters is different. Could you please help me to give a more optimized way? Tks.

http://plnkr.co/edit/DSn0JDDShOXvuXXF9PP2?p=preview

like image 270
Hieu Tran Avatar asked Dec 03 '22 22:12

Hieu Tran


1 Answers

Based on @notme's answer I created the following gist for my own version of an auto-resizing input angular directive:

https://gist.github.com/Zmaster/6923413

Here is the code:

Template:

<span>
  <input type="text" ng-model="value">
  <span style="visibility:hidden; position:absolute; left:-1000; top:-1000;">{{value}}</span>
</span>

Directive:

angular.module('autoSizeInput', []) 
  .directive('autoSizeInput', function() {
    return {
      replace: true,
      scope: {
        value: '=inputValue'
      },  
      templateUrl: 'templates/directives/autoSizeInput.html',
      link: function(scope, element, attrs) {
        var elInput = element.find('input');
        var elSpan = element.find('span');
        elSpan.html(elInput.val());

        scope.$watch('value', function(value) {
          if(value) {
            elSpan.html(elInput.val());
            elInput.css('width', (elSpan[0].offsetWidth + 10) + 'px');
          }   
        }); 
      }   
    };  
  });
like image 78
zbrunson Avatar answered Dec 28 '22 23:12

zbrunson