簡體   English   中英

如何從值的Angular下拉列表中獲取ID?

[英]How to get ID from Angular dropdown from value?

正如您在代碼中看到的那樣,我在availableCars列表中有一個列出了汽車A,B和C以及相應的ID。 我已經從服務中選擇了汽車。 它不僅是汽車名稱,而且不是對象。 用戶可以選擇其他汽車,但是在更改時,我必須將汽車ID發送給其他服務。 有沒有最簡單的方法可以實現我的目標?

 (function(angular) { 'use strict'; angular.module('ngrepeatSelect', []) .controller('ExampleController', ['$scope', function($scope) { $scope.carName = (function getCarNameFromService(){ return 'Car B'; })(); $scope.availableCars = [ {id: '1A', name: 'Car A'}, {id: '2B', name: 'Car B'}, {id: '3C', name: 'Car C'} ] }]); })(window.angular); 
 <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-ngrepeat-select-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-app="ngrepeatSelect"> <div ng-controller="ExampleController"> <form name="myForm"> <label for="repeatSelect"> Repeat select: </label> <select name="repeatSelect" id="repeatSelect" ng-model="carName"> <option ng-repeat="option in availableCars" value="{{option.name}}">{{option.name}}</option> </select> </form> <hr> <tt>selected car name = {{carName}}</tt><br/> <tt>selected car id = ???</tt><br/> </div> </body> </html> 

您可以使用“ ng-options”,而不是在select內的“ option”元素上使用ng-repeat。 ng-options

我創建了一個plnkr來說明您的示例。 一些關鍵代碼如下:

JS

  var carName = "Car B"; //name provided to this controller 

    $scope.availableCars =  [
       {id: '1A', name: 'Car A'},
       {id: '2B', name: 'Car B'},
       {id: '3C', name: 'Car C'}
     ]

     $scope.selectedCar = $scope.availableCars.filter(function(car){
         return car.name === carName;
     })[0];

    $scope.selectedId = $scope.selectedCar.id;

     $scope.updateCar = function(id){
         $scope.selectedId = id;
     }

的HTML

<form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select ng-options="car as car.name for car in availableCars" ng-model="selectedCar" ng-change="updateCar(selectedCar.id)"></select>
  </form>

注意html中的“ ng-change”和“ ng-options”。

用戶可以選擇其他汽車,但是在更改時,我必須將汽車ID發送給其他服務

您可以為此使用ng-change

<select ng-change="sendInfo(...)" ...>
...
</select>

實際上,我建議將汽車ID(而不是汽車名稱)綁定到模型。 或汽車對象,請您切換到ng-options 這樣,您可以發送選定的ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM