Reputation: 649
As you can see in the code, I have a list cars Car A,B, and C with corresponding ids in availableCars list. I’m getting already chosen car from a service. It is not an object just the car name. User has option to choose different car but on change, I have to send car id to other service. Is there any simplest way to achieve my goal?
(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>
Upvotes: 0
Views: 2256
Reputation: 664
Rather than using an ng-repeat on the "option" element inside of a select, you can use "ng-options". ng-options
I created a plnkr to illustrate your example. Some of the key pieces of code are as follows:
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;
}
and
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>
Notice the "ng-change" and the "ng-options" in the html.
Upvotes: 1
Reputation: 28359
User has option to choose different car but on change, I have to send car id to other service
You could use ng-change
for that:
<select ng-change="sendInfo(...)" ...>
...
</select>
Actually, I would advise to bind to the model the car id instead of the car name. Or a car object, providing you switch to ng-options
. That way you could send the selected id.
Upvotes: 0