beckah beckah - 3 months ago 9
AngularJS Question

Get currently selected object as an argument for another field in Angular

I have a select box that outputs all car objects in cars-array as a select option

<select name="car">
<option ng-repeat="car in cars" ng-value="car">
//car.car_name//
</option>
</select>


I want to then output all options available with a checkbox, and "check" the option if it's available for that car

<table id="options">
<tr ng-repeat="option in options">
<td>
//option//
</td>
<td>
<input type="checkbox" ng-checked="checkCarOption(car,option)"></input>
</td>
</tr>
</table>


How do I make sure that the
car
sent into the
checkCarOption()
is the car that's currently selected?

Answer

You just need to set ng-model on the select:

<select name="car" ng-model="selectedCar">

And then you can do

checkCarOption(option)

and in the function compare it to $scope.selectedCar

In fact, you should not be doing ng-repeat on option elements. you should be using ng-options on the select element. You will run into really weird bugs later on if you don't.

<select ng-options="car as car.name for car in cars" ng-model="selectedCar" name="car"></select>