検索する

下記コードは、script.jsに書かれた検索方法です。

<html ng-app>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
 <script src="script.js"></script>

 <div ng-controller="searchCtrl">
  <p><input type="text" ng-model="query.name"></p>
  <ul>
   <li ng-repeat="item in items|filter:query">{{item.name}} {{item.price}}</li>
  </ul>
 </div>
</html>
				
var searchCtrl = function($scope) {
	$scope.items = [
	               {"name":"book","price":2520},
	               {"name":"kettle","price":1980},
	               {"name":"pc","price":69800},
	               {"name":"cosme","price":1540},
	               {"name":"software","price":27400},
	               {"name":"candy","price":10.5},
	               {"name":"ice","price":128},
	               {"name":"chiken","price":4580},
	               {"name":"cake","price":2580},
	               {"name":"drink","price":130},
	               {"name":"cd","price":1000}
	];
}
				

検索のデモ

  • {{item.name}} {{item.price}}

解説

重要なポイント

  • ng-model="query.name"
  • item in items|filter:query

[ng-model="query.name"]と[item in items|filter:query]でitemsの中のnameを検索範囲としています。 [ng-model="query.name"]が[ng-model="query"]の場合、[name][price]両方とも検索対象となります。 [ng-model="query.price"]にすると[price]だけ検索対象となります。