玩转angularJs——通过自定义ng-model,不仅仅只是input可以实现双向数据绑定

 

体验更优排版请移步原文http://blog.kwin.wang/programming/angularJs-user-defined-ngmodel.html

 

angularJs双向绑定特性在开发中很方便很实用,但是由于ng-model一般只能挂在input上,因此我们需要自定义ng-model来在div等元素上使用该标签。

自定义指令:

 1 //自定义ngModel的属性
 2     .directive('contenteditable', ['$window', function() {
 3         return {
 4             restrict: 'A',
 5             require: '?ngModel', // 此指令所代替的函数
 6             link: function(scope, element, attrs, ngModel) {
 7                 if (!ngModel) {
 8                     return;
 9                 } // do nothing if no ng-model
10                 // Specify how UI should be updated
11                 ngModel.$render = function() {
12                     element.html(ngModel.$viewValue || '');
13                 };
14                 // Listen for change events to enable binding
15                 element.on('blur keyup change', function() {
16                     scope.$apply(readViewText);
17                 });
18                 // No need to initialize, AngularJS will initialize the text based on ng-model attribute
19                 // Write data to the model
20                 function readViewText() {
21                     var html = element.html();
22                     // When we clear the content editable the browser leaves a <br> behind
23                     // If strip-br attribute is provided then we strip this out
24                     if (attrs.stripBr && html === '<br>') {
25                         html = '';
26                     }
27                     ngModel.$setViewValue(html);
28                 }
29             }
30         }
31     }])

页面中div可以这样使用ng-model:

1 <div class="icon-arrow-title title-color-2" contenteditable="true" ng-model="param.MobileNum" style="right: 15px;"></div>

 

这样,双向数据绑定就可以了。

 

转载于:https://www.cnblogs.com/kaidarwang/p/6891032.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值