續sf angularjs學習筆記第四章
1,自定義filter
<!doctype html>
<html lang='en' >
<head>
<title>自定義filter</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
</head>
<body ng-app='app' ng-controller="ctrl">
<h1>{{pageHeading | titleCase}}</h1>
<script>
function ctrl($scope) {
$scope.pageHeading = 'behold the majesty of your page title';
}
var APP = angular.module('app', []);
APP.filter('titleCase', function() {
var titleCaseFilter = function(item) {
var words = item.split(' ');//split() 方法用於把一個字符串分割成字符串數組。stringObject.split(separator(字符串或正則表達式,從該參數指定的地方分割 stringObject。),howmany(該參數可指定返回的數組的最大長度))
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);//charAt() 方法可返回指定位置的字符。slice(start(要抽取的片斷的起始下標),end(緊接着要抽取的片段的結尾的下標)) 方法可提取字符串的某個部分,並以新的字符串返回被提取的部分。
}
return words.join(' ');
};
return titleCaseFilter;
});
</script>
</body>
</html>
這個demo的作用是將’behold the majesty of your page title’每一個單詞的第一個字母大寫,自定義一個filter titleCase
頁面顯示如下: