在angular中,我們使用ajax向接口獲取數(shù)據(jù)時,通常需要對從接口獲取數(shù)據(jù)進行轉(zhuǎn)換,例如在約定中,status:0代表著狀態(tài)為上線,當我們從接口文檔獲取到數(shù)據(jù)status:0時,需要把它轉(zhuǎn)換為“上線”兩個字,這時候就需要用到angular的filter功能對數(shù)據(jù)進行轉(zhuǎn)換。
過濾器(filter)正如其名,作用就是接收一個輸入,通過某個規(guī)則進行處理,然后返回處理后的結(jié)果。主要用在數(shù)據(jù)的格式化上。例如獲取一個數(shù)組中的元素,對數(shù)組中的元素進行替換等。下面簡單的介紹也filter結(jié)合constant替換數(shù)據(jù)使用方法。
<body ng-app="myApp" ng-controller="myAppCtrl">
<div>
<div ng-repeat="x in what">
{{x.name | replaceHello}}<br/>
</div>
</div>
第一句定義一個angular應用,名字為myApp,并且定義一個控制器:controller,名字為myAppCtrl
<body ng-app="myApp" ng-controller="myAppCtrl">
第二句使用ng-repeat循環(huán)輸出指定次數(shù)的html元素。
<div ng-repeat="x in what">
然后使用過濾器對輸出的數(shù)據(jù)進行過濾處理。x.name為要過濾的數(shù)據(jù),replaceHello為過濾器名字:
{{x.name | replaceHello}}<br/>
然后是js,給what附上數(shù)據(jù):
<script>
var app = angular.module("myApp", []);
app.controller("myAppCtrl", ["$scope", function ($scope) {
$scope.what=[{name:'0',age:2},{name:'1',age:3}]
}]);
</script>
如果不進行過濾,它的效果應該是這樣的:

然后我們對數(shù)據(jù)進行過濾,我想要的效果是,數(shù)據(jù)為0是我把他替換成‘zero’,數(shù)據(jù)為1時我把他替換成‘one’,所以我先使用angular.constant定義一個常量,常量名為type:
app.constant('type',{
0:'zero',
1:'one'
});
然后我們把他注入到angular過濾器,這里的replaceHello是上面寫的過濾器名字,index是我們輸入的數(shù)據(jù)。:
app.filter('replaceHello', function (type) {
return function (index) {
console.log(type);
return type.index
}
});
然后打開網(wǎng)頁,發(fā)現(xiàn)一片空白,
后來發(fā)現(xiàn),使用對象屬性時,使用點表示法是無法通過變量訪問到屬性的。也就是,上面的type.index的index并不是 return function(index)里的index,它是type的一個未定義的屬性,
所以在這里我們可以改用方括號的方法訪問對象的數(shù)據(jù),“方括號的語法主要優(yōu)點是可以通過變量來訪問屬性,-js高程85頁”,所以上面的代碼return type.index改為
return type[index]
再打開網(wǎng)頁:

發(fā)現(xiàn)數(shù)據(jù)已經(jīng)替換成功了。
下面附上所有代碼
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myAppCtrl">
<div>
<div ng-repeat="x in what">
{{x.name |replaceHello}}<br/>
</div>
</div>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.constant('type',{
0:'zero',
1:'one'
});
app.controller("myAppCtrl", ["$scope", function ($scope) {
$scope.what=[{name:'0',age:2},{name:'1',age:3}]
}]);
//自定義過濾器
app.filter('replaceHello', function (type) {
return function (index) {
console.log(type);
return type[index]
}
});
</script>
</body>
</html>