Programing

AngularJS 'ng-options'지시문과 함께 $ index를 사용합니까?

lottogame 2020. 12. 6. 20:50
반응형

AngularJS 'ng-options'지시문과 함께 $ index를 사용합니까?


select다음을 사용하여 배열을 태그에 바인딩한다고 가정합니다 .

<select ng-model="selData" ng-options="$index as d.name for d in data">

이 경우 관련 option태그에는 일련의 인덱스 값이 할당됩니다. (0, 1, 2, ...) 그러나 드롭 다운에서 무언가를 선택하면의 값 selData이에 바인딩됩니다 undefined. 바인딩이 실제로 작동해야합니까?

반면에 다음을 대신 수행한다고 말합니다.

<select ng-model="selData" ng-options="d as d.name for d in data">

여기서 option태그는 동일한 인덱스를 갖지만 전체 객체는 변경시 바인딩됩니다. 디자인에 의해 이런 식으로 작동합니까, 아니면 단순히 AngularJS의 멋진 버그 또는 부작용입니까?


$ index는 선택이 아니라 ng-repeat에 대해 정의됩니다. 나는 이것이 undefined. (그래서, 이것은 작동하지 않습니다.)

Angular는 전체 개체에 대한 바인딩을 지원합니다. 문서는이를 나타 내기 위해 더 잘 표현 될 수 있지만, "선택 모델을 문자열이 아닌 값에 바인딩하려면 ngRepeat 대신 ngOptions ...를 사용해야합니다."라는 힌트를 제공합니다.


배열은 JavaScript의 객체와 매우 유사하므로 "객체 데이터 소스"구문을 사용할 수 있습니다. 트릭은에 괄호ng-options부분 :

var choices = [
  'One',
  'Two',
  'Three'
];

템플릿에서 :

<select
  ng-model="model.choice"
  ng-options="idx as choice for (idx, choice) in choices">
</select>

결국, model.choice값은 0, 1 또는 2가됩니다. 0이면 One; 1 Two이 표시 되지만 모델에서는 인덱스 값만 표시됩니다.

나는 PACKT Publishing의 "Mastering Web Application Development with AngularJS"에서이 정보를 수정했으며, Angular 참조 문서에서 select .


사용할 수 $index없지만 시도 할 수 있기 때문에 indexOf.

HTML

<div ng-app ng-controller="MyCtrl">
    <select 
          ng-model="selectedItem"
          ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select>
    selectedItem: {{selectedItem}}
</div>

제어 장치

function MyCtrl($scope) {
    $scope.values = ["Value1","Value2"];
    $scope.selectedItem = 0;
}

데모 Fiddle

논평:

Array.prototype.indexOf IE7 (8)에서는 지원되지 않습니다.


<option>태그에 ng-value = '$ index'를 사용할 수도 있습니다 .

<select ng-model="selData">
 <option ng-repeat="d in data track by $index" ng-value="$index">
   {{d.name}}
 </option>
</select>

$index내부 선택 태그를 사용하지 마십시오 . $index배열 인덱스를 값이나 옵션으로 사용하려면 옵션 태그 내에서 사용하십시오 .

<option ng-repeat="user in users" value="{{user.username}}">{{$index+1}}</option>

내부 값을 사용하려면 값 속성에 다음과 같은 바인딩 표현식으로 넣으십시오.

<option ng-repeat="user in users" value="{{$index+1}}">{{user.username}}</option>

내 컨트롤러 코드는 다음과 같습니다.

var users = ['username':'bairavan', 'username':'testuser'];

참고 URL : https://stackoverflow.com/questions/13916726/using-index-with-the-angularjs-ng-options-directive

반응형