AngularJs學習筆記__6、自定義過濾器,阿拉伯數字金額轉漢字金額

雖然,AngularJs內置了一些過濾器,但是有些時候,我們需要自己定義一些過濾器。下面就是一個阿拉伯數字金額轉漢字金額的自定義過濾器。

不多說直接上源碼:
filter.js

var filterApp=angular.module('FilterApp', [])
filterApp.controller('AmountFilter',function(){
	
});

filterApp.filter('Chinese',function(){
	return function(input){
		var numberValue=new String(Math.round(input*100)); // 數字金額
		var chineseValue=""; // 轉換後的漢字金額
		var String1 = "零壹貳叄肆伍陸柒捌玖"; // 漢字數字
		var String2 = "萬仟佰拾億仟佰拾萬仟佰拾元角分"; // 對應單位
		var len=numberValue.length; // numberValue 的字符串長度
		var Ch1; // 數字的漢語讀法
		var Ch2; // 數字位的漢字讀法
		var nZero=0; // 用來計算連續的零值的個數
		var String3; // 指定位置的數值
		if(len>15){
		alert("超出計算範圍");
		return "";
		}
		if (numberValue==0){
		chineseValue = "零元整";
		return chineseValue;
		}

		String2 = String2.substr(String2.length-len, len); // 取出對應位數的STRING2的值
		for(var i=0; i<len; i++){
		String3 = parseInt(numberValue.substr(i, 1),10); // 取出需轉換的某一位的值
		if ( i != (len - 3) && i != (len - 7) && i != (len - 11) && i !=(len - 15) ){
		if ( String3 == 0 ){
		Ch1 = "";
		Ch2 = "";
		nZero = nZero + 1;
		}
		else if ( String3 != 0 && nZero != 0 ){
		Ch1 = "零" + String1.substr(String3, 1);
		Ch2 = String2.substr(i, 1);
		nZero = 0;
		}
		else{
		Ch1 = String1.substr(String3, 1);
		Ch2 = String2.substr(i, 1);
		nZero = 0;
		}
		}
		else{ // 該位是萬億,億,萬,元位等關鍵位
		if( String3 != 0 && nZero != 0 ){
		Ch1 = "零" + String1.substr(String3, 1);
		Ch2 = String2.substr(i, 1);
		nZero = 0;
		}
		else if ( String3 != 0 && nZero == 0 ){
		Ch1 = String1.substr(String3, 1);
		Ch2 = String2.substr(i, 1);
		nZero = 0;
		}
		else if( String3 == 0 && nZero >= 3 ){
		Ch1 = "";
		Ch2 = "";
		nZero = nZero + 1;
		}
		else{
		Ch1 = "";
		Ch2 = String2.substr(i, 1);
		nZero = nZero + 1;
		}
		if( i == (len - 11) || i == (len - 3)){ // 如果該位是億位或元位,則必須寫上
		Ch2 = String2.substr(i, 1);
		}
		}
		chineseValue = chineseValue + Ch1 + Ch2;
		}

		if ( String3 == 0 ){ // 最後一位(分)爲0時,加上“整”
		chineseValue = chineseValue + "整";
		}

		return chineseValue;

	};
});
filterMoney.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="FilterApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/filter.js"></script>
</head>
<body>
	<div ng-Controller="AmountFilter">
		金額:<input type="text" ng-model="Amount"/>
		{{Amount | Chinese}}
	</div>

</body>
</html>
效果如下:




發佈了71 篇原創文章 · 獲贊 12 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章