AngularJS實(shí)現(xiàn)Input格式化的方法
本文實(shí)例講述了AngularJS實(shí)現(xiàn)Input格式化的方法。分享給大家供大家參考,具體如下:
今天在Angular中文群有位同學(xué)問到:如何實(shí)現(xiàn)對input box的格式化。如下的方式對嗎?
<input type="text" ng-model="demo.text | uppercase" />
這當(dāng)然是不對的。在Angular中filter(過濾器)是為了顯示數(shù)據(jù)的格式,它將$scope上的Model數(shù)據(jù)格式化View顯示的數(shù)據(jù)綁定到DOM之上。它并不會負(fù)責(zé)ngModel的綁定值的格式化。
在Angular中ngModel作為Angular雙向綁定中的重要組成部分,負(fù)責(zé)View控件交互數(shù)據(jù)到$scope上Model的同步。當(dāng)然這里存在一些差異,View上的顯示和輸入都是字符串類型,而在Model上的數(shù)據(jù)則是有特定數(shù)據(jù)類型的,例如常用的Number、Date、Array、Object等。ngModel為了實(shí)現(xiàn)數(shù)據(jù)到Model的類型轉(zhuǎn)換,在ngModelController中提供了兩個管道數(shù)組$formatters和$parsers,它們分別是將Model的數(shù)據(jù)轉(zhuǎn)換為View交互控件顯示的值和將交互控件得到的View值轉(zhuǎn)換為Model數(shù)據(jù)。它們都是一個數(shù)組對象,在ngModel啟動數(shù)據(jù)轉(zhuǎn)換時(shí),會以UNIX管道式傳遞執(zhí)行這一系列的轉(zhuǎn)換。Angular允許我們手動的添加$formatters和$parsers的轉(zhuǎn)換函數(shù)(unshift、push)。同時(shí)在這里也是做數(shù)據(jù)驗(yàn)證的最佳時(shí)機(jī),能夠轉(zhuǎn)換意味應(yīng)該是合法的數(shù)據(jù)。
同時(shí),我們也可以利用Angular指令的reuqire來獲取到這個ngModelController。如下方式來使用它的$parses和$formaters:
.directive('textTransform', [function() { return { require: 'ngModel', link: function(scope, element, iAttrs, ngModelCtrl) { ngModelCtrl.$parsers.push(function(value) { ... }); ngModelCtrl.$formatters.push(function(value) { ... }); } }; }]);
因此,開篇所描述的輸入控件的大寫格式化,則可以利用ngModelController實(shí)現(xiàn),在對于View文字大小的格式化,這個特殊的場景下,利用css特性text-transform會更簡單。所以實(shí)現(xiàn)如下:
.directive('textTransform', function() { var transformConfig = { uppercase: function(input){ return input.toUpperCase(); }, capitalize: function(input){ return input.replace( /([a-zA-Z])([a-zA-Z]*)/gi, function(matched, $1, $2){ return $1.toUpperCase() + $2; }); }, lowercase: function(input){ return input.toLowerCase(); } }; return { require: 'ngModel', link: function(scope, element, iAttrs, modelCtrl) { var transform = transformConfig[iAttrs.textTransform]; if(transform){ modelCtrl.$parsers.push(function(input) { return transform(input || ""); }); element.css("text-transform", iAttrs.textTransform); } } }; });
則,在HTML就可以如下方式使用指令:
<input type="text" ng-model="demo.text" text-transform="capitalize" /> <input type="text" ng-model="demo.text" text-transform="uppercase" /> <input type="text" ng-model="demo.text" text-transform="lowercase" />
效果參見jsbin demo: http://jsbin.com/baqaso/edit?html,js,output
在這里利用了css text-transform特性,對于其它的方式,我們可以使用keydown、keyup、keypress等來實(shí)現(xiàn)。如inputMask和ngmodel-format。
希望本文所述對大家AngularJS程序設(shè)計(jì)有所幫助。
相關(guān)文章
AngularJS實(shí)現(xiàn)與Java Web服務(wù)器交互操作示例【附demo源碼下載】
這篇文章主要介紹了AngularJS實(shí)現(xiàn)與Java Web服務(wù)器交互操作的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了AngularJS前臺ajax提交與javascript后臺處理的完整流程與實(shí)現(xiàn)技巧,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2016-11-11詳解Angular調(diào)試技巧之報(bào)錯404(not found)
本篇文章主要介紹了詳解Angular調(diào)試技巧之報(bào)錯404(not found),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01angularjs實(shí)現(xiàn)table增加tr的方法
下面小編就為大家分享一篇angularjs實(shí)現(xiàn)table增加tr的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02