■ Front-End ■/AngularJs

[AngularJS] 헤더를 클릭하여 테이블에 출력한 데이터를 정렬

한길(One Way) 2023. 2. 22.

SPA 작성을 쉽게 하는 자바스크립트 웹 프레임워크이다.

 

 
AngularJS에서 JSON 형식의 데이터를 테이블에 표시한 뒤 헤더를 클릭하여 데이터를 정렬하는 예제다. 먼저 books이라는 데이터를 선언하고 orderByMe() 함수를 정의하는데 파라미터를 입력받아 myOrderBy에 저장합니다. 

      angular.module('myApp', []).controller('myCtrl'function($scope) {

           $scope.books = [ {

           ... (아래의 코드를 참조) ...

           } ];

 

           $scope.orderByMe = function(x) {

                 $scope.myOrderBy = x;

           }

      });

 

 

ng-repeat를 사용하여 JSON 형식의 데이터를 반복하여 출력한다. 여기서 orderBy:myOrderBy라고 필터를 적용하였는데 ng-click으로 선언한 헤더를 클릭할 때 해당 값이 myOrderBy에 전달되고 바로 바인딩되어 테이블에 클릭한 칼럼의 이름으로 정렬된다.

 

       <table border="1" width="100%">

             <tr>

                  <th ng-click="orderByMe('name')">Name</th>

                  <th ng-click="orderByMe('price')">Price</th>

             </tr>

             <tr ng-repeat="x in books | orderBy:myOrderBy">

                  <td>{{x.name}}</td>

                  <td>{{x.price}}</td>

             </tr>

       </table>

 

 

예제의 전체코드이다.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" type="text/javascript"></script>
<script>
      angular.module('myApp', []).controller('myCtrl', function($scope) {
           $scope.books = [ {
                 "id" : "id1",
                 "name" : "MongoDB",
                 "price" : 16000
           }, {
                 "id" : "id2",
                 "name" : "Express",
                 "price" : 12000
           }, {
                 "id" : "id3",
                 "name" : "AngularJS",
                 "price" : 13000
           }, {
                 "id" : "id4",
                 "name" : "Node.js",
                 "price" : 15000
           }, {
                 "id" : "id5",
                 "name" : "jQuery Mobile",
                 "price" : 11000
           } ];
 
           $scope.orderByMe = function(x) {
                 $scope.myOrderBy = x;
           }
      });
</script>
</head>
 
<body>
      <div ng-app="myApp" ng-controller="myCtrl">
           <table border="1" width="100%">
                 <tr>
                      <th ng-click="orderByMe('name')">Name</th>
                      <th ng-click="orderByMe('price')">Price</th>
                 </tr>
                 <tr ng-repeat="x in books | orderBy:myOrderBy">
                      <td>{{x.name}}</td>
                      <td>{{x.price}}</td>
                 </tr>
           </table>
      </div>
      <hr>
</body>
</html>

 

 

아래와 같이 화면에 표시된다. 첫 화면에서는 컨트롤러에서 할당한 값이 바로 표시된다.

 

Name 헤더를 클릭하면 Name으로 정렬되어 표시된다.

 

Price 헤더를 클릭하면 Price로 정렬되어 표시된다.

 

728x90

댓글