AngularJS 指令输入宽度通过 keyup 调整大小 [英] AngularJS directive input width resize by keyup

查看:25
本文介绍了AngularJS 指令输入宽度通过 keyup 调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个指令,以便在键入时自动调整宽度的输入(如 Google 通讯录).不过好像不行,因为每个字符的宽度都不一样.你能帮我提供一个更优化的方法吗?tks.

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

推荐答案

基于@notme 的回答,我为我自己的自动调整输入角度指令版本创建了以下要点:

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

代码如下:

模板:

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

指令:

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');
          }   
        }); 
      }   
    };  
  });

这篇关于AngularJS 指令输入宽度通过 keyup 调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆