Program Club

AngularJS-선택을위한 값 속성

proclub 2020. 10. 26. 21:30
반응형

AngularJS-선택을위한 값 속성


소스 JSON 데이터는 다음과 같습니다.

[
  {"name":"Alabama","code":"AL"},
  {"name":"Alaska","code":"AK"},
  {"name":"American Samoa","code":"AS"},
  ...
]

나는 시도

ng-options="i.code as i.name for i in regions"

하지만 점점 :

<option value="?" selected="selected"></option>
<option value="0">Alabama</option>
<option value="1">Alaska</option>
<option value="2">American Samoa</option>

내가 기대하는 동안 :

<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AS">American Samoa</option>

따라서 값 속성을 가져오고 "?"를 제거하는 방법 안건?

그런데 $ scope.regions를 AJAX 요청 결과 대신 정적 JSON으로 설정하면 빈 항목이 사라집니다.


처음 시도한 것이 작동하지만 HTML은 우리가 기대하는 것과 다릅니다. 초기 "선택된 항목 없음"케이스를 처리하는 옵션을 추가했습니다.

<select ng-options="region.code as region.name for region in regions" ng-model="region">
   <option style="display:none" value="">select a region</option>
</select>
<br>selected: {{region}}

위는 다음 HTML을 생성합니다.

<select ng-options="..." ng-model="region" class="...">
   <option style="display:none" value class>select a region</option>
   <option value="0">Alabama</option>
   <option value="1">Alaska</option>
   <option value="2">American Samoa</option>
</select>

깡깡이

Angular는 값에 숫자 정수를 사용하지만 모델 (예 : $ scope.region)은 원하는대로 AL, AK 또는 AS로 설정됩니다. (숫자 값은 목록에서 옵션을 선택할 때 올바른 배열 항목을 조회하기 위해 Angular에서 사용됩니다.)

Angular가 "select"지시어를 구현하는 방법을 처음 배울 때 혼란 스러울 수 있습니다.


ng-repeat에서 직접 빌드하지 않는 한 실제로 이것을 할 수 없습니다.

<select ng-model="foo">
   <option ng-repeat="item in items" value="{{item.code}}">{{item.name}}</option>
</select>

하지만 ... 아마 그럴 가치가 없을 것입니다. 설계된대로 기능을 유지하고 Angular가 내부 작업을 처리하도록하는 것이 좋습니다. Angular는 이러한 방식으로 인덱스를 사용하므로 실제로 전체 객체를 값으로 사용할 수 있습니다. 따라서 드롭 다운 바인딩을 사용하여 문자열이 아닌 전체 값을 선택할 수 있습니다.

<select ng-model="foo" ng-options="item as item.name for item in items"></select>

{{foo | json}}

track by옵션 을 사용하면 value속성이 올바르게 작성됩니다. 예 :

<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
    <select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>

생성 :

<select>
    <option value="" selected="selected"></option>
    <option value="15">one</option>
    <option value="20">two</option>
</select>

드롭 다운에 지정된 모델이 존재하지 않으면 angular는 빈 옵션 요소를 생성합니다. 따라서 다음과 같이 선택시 모델을 명시 적으로 지정해야합니다.

<select ng-model="regions[index]" ng-options="....">

이전에 답변 한대로 다음을 참조하십시오.

AngularJS가 select에 빈 옵션을 포함하는 이유는 무엇입니까? 그리고이 바이올린

Update: Try this instead:

<select ng-model="regions[index].code" ng-options="i.code as i.name for i in regions">
</select>

or

<select ng-model="regions[2]" ng-options="r.name for r in regions">
</select>

Note that there is no empty options element in the select.


You could modify you model to look like this:

$scope.options = {
    "AL" : "Alabama",
    "AK" : "Alaska",
    "AS" : "American Samoa"
  };

Then use

<select ng-options="k as v for (k,v) in options"></select>

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):

HTML:

<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

Javascript:

App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>

and

<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.


you can use

state.name for state in states track by state.code

Where states in the JSON array, state is the variable name for each object in the array.

Hope this helps


Try it as below:

var scope = $(this).scope();
alert(JSON.stringify(scope.model.options[$('#selOptions').val()].value));

참고URL : https://stackoverflow.com/questions/13803665/angularjs-value-attribute-for-select

반응형