2016년 1월 12일 화요일

[AngularJS] ng-repeat / add item

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!-- index.html -->
<html ng-app='fruitApp'>
    <head>
        <title>ng-repeat test</title>
    </head>
    <body ng-controller='bodyController'>
        <table>
            <!-- fruis 배열에서 fuirt 아이템을 추출한다. -->
            <!-- fruis 배열의 수 만큼 반복한다. -->
            <tr ng-repeat='fruit in fruits'>
                <!-- $index는 내부변수로 fruis 배열의 인덱스가 들어간다. -->
                <td>{{$index}}</td>
                <!-- 아래와 같이 id를 이용해서 해당 페이지 상세보기 등으로 넘어갈 수 있다. -->
                <td><a href='/fruit/view/{{fruit.id}}'>{{fruit.name}}</a></td>                
            </tr>
        <table>
        <br>
        <!-- ng-click은 버튼이 클릭되면 호출된다. -->
        <button ng-click="insertButton()"> insert item </button>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
        <script>
            var app = angular.module('fruitApp',[]);
            var __function = function($scope){
                // dom 로드시 컨트롤러에 의해서 호출되며, 배열에 아래 아이템을 추가한다.
                $scope.fruits = [
                {name:'banana', id:1},
                {name:'apple', id:2}
                ];
                // button을 누르면 호출되며, splice 함수로 추가한다.
                // splice function : http://www.w3schools.com/jsref/jsref_splice.asp
                // The splice() method adds/removes items to/from an array, and returns the removed item(s)
                // Note: This method changes the original array.
                $scope.insertButton = function(){
                    $scope.fruits.splice(0,0,{name:'jteve', id:'4'});
                }
            }
            app.controller('bodyController',__function);
       </script>
    </body>
</html>
 
 
cs

댓글 없음:

댓글 쓰기