Contents
see List작성일 2016. 08. 18.
AngularJS ng-options 완벽 가이드
ng-options는 AngularJS에서 select 드롭다운을 동적으로 생성하는 디렉티브입니다. ng-repeat보다 성능이 우수하고 객체 바인딩을 지원합니다.
1. 기본 문법
<!-- 배열에서 옵션 생성 -->
<select ng-model="selectedItem"
ng-options="item for item in items">
</select>
<!-- 기본 선택 옵션 추가 -->
<select ng-model="selectedItem"
ng-options="item for item in items">
<option value="">선택하세요</option>
</select>
2. 객체 배열 사용
// Controller
$scope.users = [
{id: 1, name: "홍길동", dept: "개발팀"},
{id: 2, name: "김철수", dept: "기획팀"},
{id: 3, name: "이영희", dept: "디자인팀"}
];
<!-- 표시값 as 실제값 for 아이템 in 배열 -->
<select ng-model="selectedUser"
ng-options="user.name for user in users">
</select>
<!-- ID를 값으로, 이름을 라벨로 -->
<select ng-model="selectedUserId"
ng-options="user.id as user.name for user in users">
</select>
3. 그룹화 (group by)
<!-- 부서별 그룹화 -->
<select ng-model="selectedUser"
ng-options="user.name group by user.dept for user in users">
</select>
<!-- 결과 -->
<optgroup label="개발팀">
<option>홍길동</option>
</optgroup>
<optgroup label="기획팀">
<option>김철수</option>
</optgroup>
4. 정렬 및 필터링
<!-- 이름순 정렬 -->
<select ng-model="selected"
ng-options="u.name for u in users | orderBy:name">
</select>
<!-- 필터링 -->
<select ng-model="selected"
ng-options="u.name for u in users | filter:{dept:개발팀}">
</select>
5. 비활성화 옵션
<!-- disable when 조건 -->
<select ng-model="selected"
ng-options="u.name disable when u.inactive for u in users">
</select>
ng-options vs ng-repeat 비교
| 구분 | ng-options | ng-repeat |
|---|---|---|
| 성능 | 우수 (최적화됨) | 상대적 느림 |
| 객체 바인딩 | 지원 | 문자열만 |
| 빈 옵션 | 별도 추가 필요 | 함께 작성 |
| track by | 지원 | 지원 |
주의사항
- ng-model 필수 - 없으면 동작하지 않음
- 초기값 설정시 참조 일치 필요
- track by로 성능 최적화 가능
javascript
| No | 작성일 | Title |
|---|---|---|
| 1180 | 2016. 11. 28. | [ AngularJS ] angularJs jquery selector |
| 1141 | 2016. 11. 01. | [ AngularJS ] ng-if 의 경우 상위 디렉브를 생성한다. |
| 1139 | 2016. 10. 21. | [ javascript ] 반응형 웹에서 PC 버전보기 구현 |
| 1076 | 2016. 09. 09. | [ AngularJS ] promise then 사용 |
| 1075 | 2016. 09. 07. | [ AngularJS ] 형제 태그 ng-repeat |
| 1074 | 2016. 09. 07. | [ AngularJS ] 의 이벤트 전파 |
| 1041 | 2016. 08. 18. | [ AngularJS ] json parsing spring ajax (and $$hashKey error ) |
| 1040 | 2016. 08. 18. | [ AngularJS ] select option ng-options |
| 1039 | 2016. 08. 18. | [ AngularJS ] ng-repeat 에서 ng-model 사용시 제대로 작동안할때 |
| 1038 | 2016. 08. 16. | [ AngularJS ] 어느 위치에서나 scope 에 접근하기 (전역,지역) |