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

时间:2023-03-10 03:39:20
玩转angularJs——通过自定义ng-model,不仅仅只是input可以实现双向数据绑定

体验更优排版请移步原文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>

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