angularjs输入框自动变化高度(可输入div并运用ng-model)附带placeholder效果

angular其实不再需要input和textarea标签来做输入功能,只需要给div加个h5属性contenteditable="true"即可使用ng-model实现双向绑定,和高度自适应的功能,

苹果手机不支持h5属性 contenteditable="true",需要在这个div中添加样式-webkit-user-select:text 

这里的ng-model只能绑定对象中的某一个元素,如ng-model=“content.item”

   div{

     -webkit-user-select:text; 

   }

 

    /*为空时显示 element attribute content*/

 

    div :empty:before{

 

      content: attr(placeholder);   /* element attribute*/

 

      color:#red;              /*content: 'this is content';*/

 

    }

 

    /*焦点时内容为空*/

 

    div :focus:before{

 

      content:none;

 

    }

 

html代码

<div contenteditable="true" class="texttitle zkht-create-answer" ng-model="content.item"></div>

 

directive.js

app.directive('contenteditable', function() {
  return {
    restrict: 'A', // 只用于属性
    require: '?ngModel', // get a hold of NgModelController
  link: function(scope, element, attrs, ngModel) {
    if (!ngModel) {
      return;
    } 
    // Specify how UI should be updated
    ngModel.$render = function() {
      element.html(ngModel.$viewValue || '');
    };
    // Listen for change events to enable binding
    element.on('blur keyup change', function() {
      scope.$apply(readViewText);
    });
    // No need to initialize, AngularJS will initialize the text based on ng-model attribute
    // Write data to the model
    function readViewText() {
      var html = element.html();
      // When we clear the content editable the browser leaves a <br> behind
      // If strip-br attribute is provided then we strip this out
      if (attrs.stripBr && html === '<br>') {
        html = '';
      }
      ngModel.$setViewValue(html);
    }
  }
};

转载于:https://www.cnblogs.com/cutone/p/5859336.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值