-
AngularJS에서 CRUD 구현하기 #3Web Programming/Angular JS 2020. 9. 11. 15:57반응형
마지막으로 Update를 구현해보도록 한다.
아이디를 받아오는 Delete와 생성을 가능하게 하는 Create가 있으니 그렇게 어렵지 않다.
간단한 구현을 목표로 하고있으므로 따로 창을 생성하지 않고 input 태그를 그대로 사용하자.
<table border="1"> <tr> <td style="width: 50px">No.</td> <td style="width: 200px">Title</td> <td style="width: 50px">Name</td> <td style="width: 50px">Update</td> <td style="width: 50px">Delete</td> </tr> <tr ng-repeat="item in boardlist"> <td style="width: 50px">{{$index+1}}</td> <td style="width: 200px">{{item.title}}</td> <td style="width: 50px">{{item.writer}}</td> <td style="width: 50px"><button type="button" ng-click="update(item.id)">Update</button></td> <td style="width: 50px"><button type="button" ng-click="remove(item.id)">Delete</button></td> </tr> </table>
게시판 table을 다음과 같이 수정한다. Delete와 마찬가지로 버튼을 구현해 update 메소드와 연결시킨다.
$scope.update = function(id) { if(!id) return; //예외처리 var idx = -1 for(var i = 0; i < $scope.boardlist.length; i++) { if($scope.boardlist[i].id === id) { idx = i; break; } } if(idx === -1) return; //예외처리 var newItem = { id : id, title : $scope.boardForm.title, writer : $scope.boardForm.writer }; $scope.boardlist.splice(idx, 1, newItem); //배열의 요소 변경 }
- id 값이 없는 경우 예외처리를 한다.
- 받아오는 id를 boardlist의 id와 비교하여 일치하면 idx에 id의 index를 저장하고, 일치하는 id가 없으면 idx에 -1을 저장한다.
- 일치하는 id값이 없을 경우의 예외처리를 한다.
- 받아온 id값과 input의 title, writer를 newItem에 저장한다.
- splice를 활용하여 해당 index의 배열을 newItem으로 변경한다.
다음과 같이 input을 채우고 Update를 누르면 해당 게시물이 수정된다.
이렇게 CRUD의 Create, Read, Update, Delete가 모두 완성되었다.
반응형'Web Programming > Angular JS' 카테고리의 다른 글
AngularJS Tutorial #1 Expressions (0) 2020.09.14 AngularJS에서 CRUD 구현하기 #2 (0) 2020.09.11 AngularJS에서 CRUD 구현하기 #1 (0) 2020.09.10 프론트엔드 프레임워크(Front-End Framework) 란? (1) 2020.09.10 Angular JS 란? (0) 2020.09.10