2016-09-07 184 views
0

我想要實現的是當我提交表單時,它應該返回我在控制檯中選擇的選項的標籤,但它將返回值選項。如何在Angular JS中提交表單時獲取輸入字段的標籤

預期結果: DXBA天空

結果得到: 迪拜

HTML

<div class="suggestField"> 
    <input type='text' list='listid' placeholder="TO" ng-model="toCity" ng- change="suggestCity(toCity)"> 
    <datalist id='listid'> 
      <option ng-repeat="item in fromSuggestData" label='{{item.PlaceId}}' value='{{item.PlaceName}}'> 
    </datalist> 
    <button ng-click="submitForm(toCity)">SUBMIT</button> 
</div> 

JS

$scope.fromSuggestData = { 
    "PlaceId": "DXBA-sky", 
    "PlaceName": "Dubai", 
    "CountryId": "AE-sky", 
    "RegionId": "", 
    "CityId": "DXBA-sky", 
    "CountryName": "United Arab Emirates" 
}, { 
    "PlaceId": "DUJ-sky", 
    "PlaceName": "Dubois", 
    "CountryId": "US-sky", 
    "RegionId": "PA", 
    "CityId": "DUJA-sky", 
    "CountryName": "United States" 
} 
$scope.submitForm = function(toCity) { 
    console.log(toCity); 
} 
+1

而是供選NG重複使用NG選項https://docs.angularjs.org/api/ng/directive/ngOptions –

+0

@MarcusH能否請你告訴我怎麼能我的解決方案使用ng-option?我是AngularJS的新手。 –

+0

Ofcourse,但請用當前的解決方案在問題中創建一個plunker或工作代碼片段。還包括完整的控制器。 –

回答

3

這裏是使用ng-option的演示。

var app = angular.module("myApp", []); 
 
app.controller("myCtrl", function($scope) { 
 
    $scope.fromSuggestData = [{ 
 
    "PlaceId": "DXBA-sky", 
 
    "PlaceName": "Dubai", 
 
    "CountryId": "AE-sky", 
 
    "RegionId": "", 
 
    "CityId": "DXBA-sky", 
 
    "CountryName": "United Arab Emirates" 
 
    }, { 
 
    "PlaceId": "DUJ-sky", 
 
    "PlaceName": "Dubois", 
 
    "CountryId": "US-sky", 
 
    "RegionId": "PA", 
 
    "CityId": "DUJA-sky", 
 
    "CountryName": "United States" 
 
    }]; 
 
    $scope.submitForm = function(toCity) { 
 
    console.log(toCity); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl" class="suggestField"> 
 
    <select id="cityname" ng-model="toCity" ng-options="item as item.PlaceName for item in fromSuggestData"> 
 
    <option value="">Select</option> 
 
    </select> 
 
    <button ng-click="submitForm(toCity.PlaceId)">SUBMIT</button> 
 
</div>

相關問題