2016-03-29 13 views
1

Seçime açısal olarak bir varsayılan seçenek eklemeye çalışıyorum ancak seçtiğimde garip bir şekilde kaybolan boş bir seçenek ekliyor.angularjs seçeneğine varsayılan seçeneği ekleyin

Nesnenin bu gibi ng-options kullanarak seçime bağlanmasını sağlıyorum.

var DocumentSearchController = function (documentsService) { 
    documentsService.getDocTypes().then(function (results) { 
     this.documentTypes = results.data; 
     this.documentTypes.unshift({ DocumentTypeID: null, Name: 'Select a Document Type' }); 
    }.bind(this)); 

nesnelerin yapısı şöyledir:: Böyle bir varsayılan seçeneği ekliyorum

[{DocumentTypeID: 1, Name: 'Blah'}] 

Sonra nesneleri bağlamak için ng-options kullanın:

<select class="form-control" 
     id="documentTypeSelector" 
     name="documentTypeSelector" 
     ng-model="vm.selectedDocumentType" 
     ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID"> 
</select> 

Sonra can sıkıcı şudur Bir öğe seçtiğimde kaldırılan boş bir seçenek gariptir.

Seçenekler de sipariş edilmiyor, bu yüzden liste anladığımın hatalı olduğundan şüpheleniyorum.

Bir varsayılan değerini bu şekilde ekleyebilir

cevap

0

:

<select class="form-control" 
     id="documentTypeSelector" 
     name="documentTypeSelector" 
     ng-model="vm.selectedDocumentType" 
     ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID"> 
    <option value="">Select a Document Type</option> 
</select> 

Düzenleme Ya da sadece binded değişkeni ng-model mevcut varsayılan bir değer atamak varsayılan <select> öğesini tanımlamak için başlat işlevini

<select class="form-control" 
     ng-init="vm.selectedDocumentType= vm.documentTypes[0]" 
     id="documentTypeSelector" 
     name="documentTypeSelector" 
     ng-model="vm.selectedDocumentType" 
     ng-options="option.Name for option in vm.documentTypes | orderBy:'option.DocumentTypeID':false track by option.DocumentTypeID"> 
</select> 
1

kullanarak Bir <option> öğesinde (veya değer). Senin durumunda vm.selectedDocumentType yılında

// given $scope.options = [1, 2, 3]; 
<select ng-init="selectedOption=1" ng-option="option for option in options" ng-model='selectedOption'> 
</select> 

Sen hiç boş seçenekler bulacaksınız ve seçilen seçenek olacaktır olabilir genel basitleştirilmiş örnekte bir vm.documentTypes[theIndexYouChoose].DocumentTypeID

Daha ayarlanmalıdır 1

İlgili konular