玩轉angularJs——通過自訂ng-model,不僅僅只是input可以有雙向繫結

來源:互聯網
上載者:User

標籤:events   function   ict   lis   自訂   通過   value   link   cti   

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-model10                 // Specify how UI should be updated11                 ngModel.$render = function() {12                     element.html(ngModel.$viewValue || ‘‘);13                 };14                 // Listen for change events to enable binding15                 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 attribute19                 // Write data to the model20                 function readViewText() {21                     var html = element.html();22                     // When we clear the content editable the browser leaves a <br> behind23                     // If strip-br attribute is provided then we strip this out24                     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>

雙向繫結就可以用了。

玩轉angularJs——通過自訂ng-model,不僅僅只是input可以有雙向繫結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.