玩轉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>

 

這樣,雙向數據綁定就可以了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM