program story

AngularJS가 select에 빈 옵션을 포함하는 이유는 무엇입니까?

inputbox 2020. 10. 2. 22:13
반응형

AngularJS가 select에 빈 옵션을 포함하는 이유는 무엇입니까?


저는 지난 몇 주 동안 AngularJS와 함께 작업 해 왔으며 실제로 나를 괴롭히는 한 가지는 http://docs.angularjs.org/api/ng 의 사양에 정의 된 모든 순열 또는 구성을 시도한 후에도 .directive : select , 여전히 선택 요소의 첫 번째 자식으로 빈 옵션이 표시됩니다.

비취는 다음과 같습니다.

select.span9(ng-model='form.type', required, ng-options='option.value as option.name for option in typeOptions');

여기 컨트롤러 :

$scope.typeOptions = [
    { name: 'Feature', value: 'feature' },
    { name: 'Bug', value: 'bug' },
    { name: 'Enhancement', value: 'enhancement' }
];

마지막으로 생성되는 HTML은 다음과 같습니다.

<select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" class="span9 ng-pristine ng-invalid ng-invalid-required">
    <option value="?" selected="selected"></option>
    <option value="0">Feature</option>
    <option value="1">Bug</option>
    <option value="2">Enhancement</option>
</select>

이를 제거하려면 어떻게해야합니까?

추신 : 이것 없이도 작동하지만 다중 선택없이 select2를 사용하면 이상하게 보입니다.


에서 option참조하는 값 ng-model이에 전달 된 옵션 집합에 존재하지 않는 경우 값이 생성됩니다 ng-options. 이것은 우발적 인 모델 선택을 방지하기 위해 발생합니다. AngularJS는 초기 모델이 정의되지 않았거나 옵션 세트에없는 것을 확인할 수 있으며 모델 값을 스스로 결정하고 싶지 않습니다.

빈 옵션을 제거하려면 컨트롤러에서 초기 값을 선택하십시오.

$scope.form.type = $scope.typeOptions[0].value;

다음은 jsFiddle입니다. http://jsfiddle.net/MTfRD/3/

간단히 말해서, 빈 옵션은 유효한 모델이 선택되지 않았 음을 의미합니다 (유효하다는 의미 : 옵션 집합에서). 이 빈 옵션을 제거하려면 유효한 모델 값을 선택해야합니다.


초기 값을 원하면 @ pkozlowski.opensource의 답변을 참조하십시오. ng-init를 사용하여 컨트롤러가 아닌 뷰에서 FYI를 구현할 수도 있습니다.

<select ng-model="form.type" required="required" ng-init="form.type='bug'"
  ng-options="option.value as option.name for option in typeOptions" >
</select>

초기 값을 원하지 않는 경우 "값이 빈 문자열로 설정된 단일 하드 코딩 된 요소를 요소에 중첩 할 수 있습니다. 그러면이 요소는 null 또는"선택되지 않음 "옵션을 나타냅니다":

<select ng-model="form.type" required="required"
  ng-options="option.value as option.name for option in typeOptions" >
    <option style="display:none" value="">select a type</option>
</select>

각도 <1.4

"null"을 옵션 중 하나에 대한 유효한 값으로 취급하는 모든 사람을 위해 ( 아래 예 에서 "null"이 typeOptions 항목 중 하나의 값이라고 상상해보십시오 ) 자동으로 추가되었는지 확인하는 가장 간단한 방법을 발견했습니다. 옵션은 ng-if를 사용하는 것입니다.

<select ng-options="option.value as option.name for option in typeOptions">
    <option value="" ng-if="false"></option>
</select>

ng-if 와 ng-hide가 아닌가? 위의 select 안에있는 첫 번째 옵션을 대상으로하는 CSS 선택기가 숨겨진 옵션이 아닌 "실제"옵션을 대상으로하기를 원하기 때문입니다. e2e 테스트를 위해 각도기를 사용하고 (어떤 이유로 든) by.css ()를 사용하여 선택 옵션을 대상으로 할 때 유용합니다.

각도> = 1.4

선택 및 옵션 지시문의 리팩토링으로 인해 사용 ng-if은 더 이상 실행 가능한 옵션이 아니므로 ng-show="false"다시 작동하도록 설정해야합니다.


누군가에게 유용 할 수도 있습니다.

ng-options 대신 일반 옵션을 사용하려면 다음과 같이 할 수 있습니다.

<select ng-model="sortorder" ng-init="sortorder='publish_date'">
  <option value="publish_date">Ascending</option>
  <option value="-publish_date">Descending</option>
</select>

모델을 인라인으로 설정합니다. ng-init를 사용하여 빈 옵션을 제거하십시오.


비슷한 일이 저에게도 발생했으며 angular 1.5 로의 업그레이드로 인해 발생했습니다. Angular의 최신 버전에서 유형ng-init대해 구문 분석되는 것 같습니다 . 이전 Angular에서는 값이 "600"인 옵션에 매핑됩니다. 즉 , Angular 1.5에서는 값이 600 인 옵션을 찾을 것으로 예상하므로이를 찾지 못합니다 . Angular는 임의의 첫 번째 항목을 삽입합니다.ng-init="myModelName=600"<option value="600">First</option><option value=600>First</option>

<option value="? number:600 ?"></option>

각도 <1.2.x

<select ng-model="myModelName" ng-init="myModelName=600">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

각도> 1.2

<select ng-model="myModelName" ng-init="myModelName='600'">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

여기에있는 수많은 답변 중에서 저에게 효과 가 있고 다음 조건을 모두 충족하는 솔루션을 다시 게시 할 것이라고 생각했습니다 .

  • ng-model이 허위 일자리 표시 자 / 프롬프트 제공 (예 : "--select region --"w. value="")
  • when ng-model value is falsy and user opens the options dropdown, the placeholder is selected (other solutions mentioned here make the first option appear selected which can be misleading)
  • allow the user to deselect a valid value, essentially selecting the falsy/default value again

enter image description here

code

<select name="market_vertical" ng-model="vc.viewData.market_vertical"
    ng-options="opt as (opt | capitalizeFirst) for opt in vc.adminData.regions">

    <option ng-selected="true" value="">select a market vertical</option>
</select>

src

original q&a - https://stackoverflow.com/a/32880941/1121919


A quick solution:

select option:empty { display:none }

Hope it helps someone. Ideally, the selected answer should be the approach but if in case that's not possible then should work as a patch.


Yes ng-model will create empty option value, when ng-model property undefined. We can avoid this, if we assign object to ng-model

Example

angular coding

$scope.collections = [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement'}
];

$scope.selectedOption = $scope.collections[0];


<select class='form-control' data-ng-model='selectedOption' data-ng-options='item as item.name for item in collections'></select>

Important Note:

Assign object of array like $scope.collections[0] or $scope.collections[1] to ng-model, dont use object properties. if you are getting select option value from server, using call back function, assign object to ng-model

NOTE from Angular document

Note: ngModel compares by reference, not value. This is important when binding to an array of objects. see an example http://jsfiddle.net/qWzTb/

i have tried lot of times finally i found it.


Though both @pkozlowski.opensource's and @Mark's answers are correct, I'd like to share my slightly modified version where I always select the first item in the list, regardless of its value:

<select ng-options="option.value as option.name for option in typeOptions" ng-init="form.type=typeOptions[0].value">
</select>


I faced the same issue. If you are posting an angular form with normal post then you will face this issue, as angular don't allow you to set values for the options in the way you have used. If you get the value of "form.type" then you will find the right value. You have to post the angular object it self not the form post.


Ok, actually the answer is way simple: when there is a option not recognized by Angular, it includes a dull one. What you are doing wrong is, when you use ng-options, it reads an object, say [{ id: 10, name: test }, { id: 11, name: test2 }] right?

This is what your model value needs to be to evaluate it as equal, say you want selected value to be 10, you need to set your model to a value like { id: 10, name: test } to select 10, therefore it will NOT create that trash.

Hope it helps everybody to understand, I had a rough time trying :)


I'm using Angular 1.4x and I found this example, so I used ng-init to set the initial value in the select:

<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.id for item in items"></select>

A simple solution is to set an option with a blank value "" I found this eliminates the extra undefined option.


This worked for me

<select ng-init="basicProfile.casteId" ng-model="basicProfile.casteId" class="form-control">
     <option value="0">Select Caste....</option>
     <option data-ng-repeat="option in formCastes" value="{{option.id}}">{{option.casteName}}</option>
 </select>

This works perfectly fine

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value=""></option>
</select>

the way it works is, that this gives the first option to be displayed before selecting something and the display:none removes it form the dropdown so if you want you can do

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value="">select an option...</option>
</select>

and this will give you the select and option before selecting but once selected it will disappear, and it will not show up in the dropdown.


This solution works for me:

<select ng-model="mymodel">    
   <option ng-value="''" style="display:none;" selected>Country</option>
   <option value="US">USA</option>
</select>

Try this one in your controller, in the same order:

$scope.typeOptions = [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement' }
];
$scope.form.type = $scope.typeOptions[0];

Here is the fix :

for a sample data like :

financeRef.pageCount = [{listCount:10,listName:modelStrings.COMMON_TEN_PAGE},    
{listCount:25,listName:modelStrings.COMMON_TWENTYFIVE_PAGE},
{listCount:50,listName:modelStrings.COMMON_FIFTY_PAGE}];

The select option should be like this:-

<select ng-model="financeRef.financeLimit" ng-change="financeRef.updateRecords(1)" 
class="perPageCount" ng-show="financeRef.showTable" ng-init="financeRef.financeLimit=10"
ng-options="value.listCount as value.listName for  value in financeRef.pageCount"
></select>

The point being when we write value.listCount as value.listName, it automatically populates the text in value.listName but the value of the selected option is value.listCount although the values my show normal 0,1,2 .. and so on !!!

In my case, the financeRef.financeLimit is actually grabbing the value.listCount and I can do my manipulation in the controller dynamically.


I would like to add that if the initial value comes from a binding from some parent element or 1.5 component, make sure that the proper type is passed. If using @ in binding, the variable passed will be string and if the options are eg. integers then the empty option will show up.

Either parse properly the value in init, or binding with < and not @ (less recommended for performance unless necessary).


Simple solution

<select ng-model='form.type' required><options>
<option ng-repeat="tp in typeOptions" ng-selected="    
{{form.type==tp.value?true:false}}" value="{{tp.value}}">{{tp.name}}</option>


A grind solution with jQuery when you haven't the control of the options

html:

<select id="selector" ng-select="selector" data-ng-init=init() >
...
</select>

js:

$scope.init = function () {
    jQuery('#selector option:first').remove();
    $scope.selector=jQuery('#selector option:first').val();
}

If you use ng-init your model to solve this problem:

<select ng-model="foo" ng-app ng-init="foo='2'">

i had the same problem, i (removed "ng-model") changed this :

<select ng-model="mapayear" id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>

to this:

<select id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>

now its working, but in my case it was cause ive deleted that scope from ng.controller, check if u didn't do the same.


Hi I had some jQUery mobile references and I removed them. With jQuery mobile any of above fixes did not work for me. ( Its great if someone can explain the conflict between jQuery Mobile and Angular JS )

https://guntucomputerhacks.blogspot.com.au/2017/10/angular-js-drop-down-first-options-vs.html


The only thing worked for me is using track by in ng-options, like this:

 <select class="dropdown" ng-model="selectedUserTable" ng-options="option.Id as option.Name for option in userTables track by option.Id">


Refer the example from angularjs documentation how to overcome these issues.

  1. Go to this documentation link here
  2. Find 'Binding select to a non-string value via ngModel parsing / formatting'
  3. There u can see there, directive called 'convertToNumber' solve the issue.

It works for me. Can also see how it works here


We can use CSS to hide the first option , But it wont work in IE 10, 11. The best way is to remove the element using Jquery. This solution works for major browser tested in chrome and IE10 ,11

Also if you are using angular , sometime using setTimeout works

$scope.RemoveFirstOptionElement = function (element) {
    setTimeout(function () {
        $(element.children()[0]).remove();
    }, 0);
};

참고URL : https://stackoverflow.com/questions/12654631/why-does-angularjs-include-an-empty-option-in-select

반응형