前回からの続きになります。
前回分の index.html にソート条件追加
Sort by: <select ng-model="orderProp"> <option value="name">Alphabetical</option> <option value="age">Newest</option> </select>
で、ソート条件を orderBy で追加
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
で以下のようになる。
<!doctype html> <html lang="ja" ng-app="phonecatApp" ng-controller="PhoneListCtrl"> <head> <meta charset="utf-8"> <title>Google Phone Gallery: {{query}}</title> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"> </head> <body> Search: <input ng-model="query"> Sort by: <select ng-model="orderProp"> <option value="name">Alphabetical</option> <option value="age">Newest</option> </select> <ul class="phones"> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script> <script src="js/controllers.js"></script> </body> </html>
コントローラでは対象のデータに属性追加とソートのデフォルトを設定だけ。
'use strict'; /* Controllers */ var phonecatApp = angular.module('phonecatApp', []); phonecatApp.controller('PhoneListCtrl', function($scope) { $scope.phones = [ {'name': 'Nexus S', 'snippet': 'Fast just got faster with Nexus S.', 'age': 1}, {'name': 'Motorola XOOM™ with Wi-Fi', 'snippet': 'The Next, Next Generation tablet.', 'age': 2}, {'name': 'MOTOROLA XOOM™', 'snippet': 'The Next, Next Generation tablet.', 'age': 3} ]; $scope.orderProp = 'age'; });