用angular做的模糊搜索
今天大家來試一試用angular做一下簡單的搜索功能吧;
首先我們需要寫html的部分,我們需要設置幾個條件,比如按什麽來排序,按升序還是降序搜索,和一個文本框來設置模糊搜索;
<nav>
<select ng-model="a">
<option value="num">按編號排序</option>
<option value="name">按姓名排序</option>
<option value="age">按年齡排序</option>
</select>
<select ng-model="b">
<option value="">升序</option>
<option value="">降序</option>
</select>
<input type="text" ng-model="s"/>
</nav>
設置上ng-model好在接下來用angular來獲取動態的值,方便我們搜索,接下來我們先寫js的部分吧;
首先我們需要先引入一個angular,在js中創建angular的模塊部分和控制臺。之後我們創建一個json文件來保存一下我們需要查詢的數據,之後我們在控制臺中獲取一下這個json
{
"xinxi":[
{"num":100,"name":"baobo","age":12},
{"num":99,"name":"paopo","age":18},
{"num":50,"name":"xinxin","age":55},
{"num":55,"name":"angular","age":20},
{"num":75,"name":"chali","age":15},
{"num":85,"name":"each","age":60},
{"num":98,"name":"hello","age":19},
{"num":68,"name":"zizizi","age":28},
{"num":66,"name":"gegege","age":56},
{"num":77,"name":"fufuf","age":43},
{"num":42,"name":"baobo","age":12},
{"num":54,"name":"menmen","age":32},
{"num":88,"name":"qqqq","age":71},
{"num":69,"name":"laowang","age":22},
{"num":53,"name":"wangwang","age":99},
{"num":1,"name":"dadad","age":88}
]
}
這是我所創建的json文件。
var app=angular.module("mk",[]);
app.controller("text",function($scope,$http){
$http.get("paixu.json").success(function(data){
$scope.data=data.xinxi
$scope.a="num"
})
});
這是我所創建用來獲取json文件的代碼;
註意$scope.a = “num”;是為了和上面獲取的動態數據相對應的,並且是讓數據先按什麽先排序。
之後我們只需要把這些數據填到html部分就可以了。
<table border="0px" id="table">
<tr>
<th>編號</th>
<th>姓名</th>
<th>年齡</th>
</tr>
<tr ng-repeat="value in data | orderBy:b+a | filter:s">
<td>{{value.num}}</td>
<td>{{value.name}}</td>
<td>{{value.age}}</td>
</tr>
</table>
ng-repeat="value in data | orderBy:b+a | filter:s;這是充分運用了angular中的過濾器屬性,orderBy是排序問題,註意一定要先把升序和降序的動態數據放到前面防止出錯,filter這個過濾器就是把我們所搜索的數據和我們的json數據庫中作比較,json中哪一下標的數組中有我們搜索的數據就顯示出來,沒有則隱藏。
用angular做的模糊搜索