게시판 즐겨찾기
편집
드래그 앤 드롭으로
즐겨찾기 아이콘 위치 수정이 가능합니다.
angular ng-repeat 사용
게시물ID : programmer_13388짧은주소 복사하기
작성자 : 푸르게
추천 : 0
조회수 : 862회
댓글수 : 0개
등록시간 : 2015/09/18 21:13:03
설명글에 말이 짧음을 이해해 주세요.
 http://m.todayhumor.co.kr/view.php?table=programmer&no=13376  
ng-repeat는 angular에서 배열 정보를 view단에 보여줄때 사용한다.  

질문? 배열의 시작, 끝에 특정 함수를 실행하고 싶다.  
** 일반적인 사용 예  
1. ng-repeat는 미리 준비된 directive 이다.

2. ng-repeat는 자체 scope를 가지고 있다.  

3. 그 스코프안에는 다음 정보들이 있다.    
     $index : 배열의 index
     $first : 배열의 처음, true / false    
     $middle: 배열의 중간, true / false    
     $last : 배열의 마지막 true / false  
     $even: 배열의 짝수, true / false
     $odd: 배열의 홀수, true / false

https://docs.angularjs.org/api/ng/directive/ngRepeat  

4. 사용예  

1
2
3
4
5
6
7
8
9
10
11
12
13
var cling = angular.module('cling', []);
 
cling.controller( 'exampleCtrl',function ($scope) {
  $scope.items = [
     'angular',
     'node',
     'mongo'
  ];
});
 
<div ng-repeat="item in items">
  tool :  {{item}}
</div>
cs


  이와 같이 사용하게 된다.  
다시 질문으로 돌아와서 시작, 끝에 특정 함수를 실행하려면 어떻게 하는가?

답을 먼저 말하자면, "directive를 만들어 사용하면 된다" 이다.  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
cling.directive('callFunction'function () {
   return {
     restrict: 'A',
     link: function ($scope, $element, $attr) {
       if ($scope.$first) {
          console.log('first item printed');
          console.log('call function 1');
       } else if ($scope.$last) {
          console.log('last item printed'); 
          console.log('call function 2');
       }
     }
   }
});
 
<div ng-repeat="item in items" call-function>
  tool :  {{item}}
</div>
cs


 1. directive는 자식으로서 scope 따로 가질 수 도 있고, 부모의 scope 안에서 동작하게 할 수 있다.

2. 한 element내에서 서로다른 directive를 써서 scope를 분리할 수 없다. (음 이해 못하면 넘어가도 상관없음)

3. 즉 ng-repeat라는 디렉티브와 같은 element에 call-function 이라는 디렉티브를 만들어 넣으면 된다.

 동작하는 코드 http://plnkr.co/edit/nx1FKR7MnZOVH9ctNix0?p=preview

 결론 directive를 만들어 사용하자.  

추가로 내용1 과 내용2가 view의 표현이 다르다면 사용방법이 옳다고 볼 수 있다. 
하지만 단지 function 를 호출하기 위해 view 단을 조작하는 것은 잘못된 접근 방법이다.

 
1
2
3
4
5
6
7
8
<div ng-repeat = 'list in data'> 
  <div ng-if='{{$index}} == 0'> // ng-reapat 가 처음일때 
    // 내용 1
  </div> 
  <div ng-if='{{$index}} == data.length-1'> // ng-reapat 가 마지막일때 
    // 내용 2
   </div> 
</div>
cs
출처
전체 추천리스트 보기
새로운 댓글이 없습니다.
새로운 댓글 확인하기
글쓰기
◀뒤로가기
PC버전
맨위로▲
공지 운영 자료창고 청소년보호