玩转angularJs——通过自定义ng-model,不仅仅只是input可以实现双向数据绑定
2024-09-03 11:04:35
体验更优排版请移步原文:http://blog.kwin.wang/programming/angularJs-user-defined-ngmodel.html
angularJs双向绑定特性在开发中很方便很实用,但是由于ng-model一般只能挂在input上,因此我们需要自定义ng-model来在div等元素上使用该标签。
自定义指令:
//自定义ngModel的属性
.directive('contenteditable', ['$window', function() {
return {
restrict: 'A',
require: '?ngModel', // 此指令所代替的函数
link: function(scope, element, attrs, ngModel) {
if (!ngModel) {
return;
} // do nothing if no ng-model
// 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);
}
}
}
}])
页面中div可以这样使用ng-model:
<div class="icon-arrow-title title-color-2" contenteditable="true" ng-model="param.MobileNum" style="right: 15px;"></div>
这样,双向数据绑定就可以了。
最新文章
- android 动画
- 20145221 《信息安全系统设计基础》实验五 简单嵌入式WEB服务器实验
- JavaScript删除-confirm
- KindEditor ---富编辑器
- VisualStudio使用小技巧——快捷键(转)
- 【BZOJ】【1022】【SHOI2008】小约翰的游戏John
- jquery1.9学习笔记 之选择器(基本元素四)
- Spring--------web应用中保存spring容器
- Openstack service default port
- PE文件简介
- java中异常处理finally和return的执行顺序
- 记录一下这次web实训的两个网站
- Apache HTTP 服务器 2.4(又名httpd)安装\配置 \启动
- 我的Java之旅 第八课 Servlet 进阶API、过滤器与监听器
- C#回调浅析(委托、接口回调)
- 怎样从外网访问内网Apache HTTP Server
- 20155229《网络对抗技术》Exp6:信息收集与漏洞扫描
- spark1.4配置安装
- C# 64位系统调用32位DLL异常解决办法(异常来自HRESULT :0x8007007E)
- ios宏定义字符串
热门文章
- [Scala]Scala学习笔记二 数组
- 第一次使用stackoverflow的寻求帮助
- I.MX6 AR8031 寄存器操作
- MySql必知必会实战练习(二)数据检索
- 查找对应jar的maven包
- python学习-实现用户密码登录,输错三次锁定
- add-apt-repository 添加
- IE 9 下的 css 陷阱
- java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream异常解决方法
- MySQL删除数据库