2017-03-24 31 views
0

我正在與HTML和角度的MVC項目。 我有一個選擇列表,根據在輸入框中輸入的名字進行選擇,但我無法獲取該ID。按名稱選擇,並獲得所選項目的角度與角

這工作,但我不明白的選擇項的ID:

<input type="text" ng-model="selectedCountry"> 
    <select class="form-control" 
    ng-model="selectedCountry" 
    ng-options="country.name as country.name for country in countries"> 
<option value="">Select Country</option> 

而且這是行不通的,因爲我不能夠通過名稱來選擇,並獲得ID :

<input type="text" ng-model="selectedCountry"> 
    <select class="form-control" 
    ng-model="selectedCountry" 
    ng-options="country.id as country.name for country in countries"> 
<option value="">Select Country</option> 

這裏是plunker:Plunker

感謝您的幫助!

回答

1

爲了第二個場景中工作,你需要得到國家的ID在你的控制器是這樣的:

$scope.selectedCountry = $scope.countries.find(function(country) { 
    return country.name === "Italy"; 
    }).id; 
+0

這是正確的!那是我想要避免的,可以通過在HTML中使用declaritive模式來避免這種情況? – MarcosF8

+0

不是我所知道的。無論是從提供的名稱(意大利)派生id還是整​​個對象,或者執行一些jQuery操作......所有選項都指向控制器代碼。 – jbrown

+0

感謝大家的幫助! – MarcosF8

0

試試這個

HTML

<input type="text" ng-model="selectedCountryId"> 
    <select class="form-control" ng-model="selectedCountryId"> 
    <option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option> 
</select> 
<div>selected country id: {{selectedCountryId}} </div> 

in controller add $scope.selectedCountryId = "";

enter image description here

希望它有助於

0

或者

<input type="text" ng-model="selectedCountry.name"> 
    <select class="form-control" 
     ng-model="selectedCountry" 
     ng-options="country as country.name for country in countries"> 
    <option value="">Select Country</option> 

    </select> 

在你的HTML在你的JavaScript

$scope.selectedCountry = {}; 

2
<select class="form-control" data-ng-change="call(country.id)" 
     ng-model="country.id" 
     ng-options="country.id as country.name for country in countries"> 
    <option value="">Select Country</option> 
    </select> 
0

我不認爲這是可能的,當你在不同的選擇模型上使用不同的鍵時使用相同的模型。

我會在這兩個模型中使用的名稱,然後從陣列獲取的ID去:

$scope.getId = function(){ 
    var co = $scope.countries.filter(function (el) { return el.name == $scope.selectedCountry }); 
     if(typeof co !== 'undefined' && co.length > 0){ 
     $scope.selectedId =co[0].id; 
     }else{ 
     $scope.selectedId = null; 
     } 
    }; 

plunker here