I am facing a challenge with two dynamic object arrays: one for colors and one for buses. The main objective is to assign a color to each bus. I have used ng-repeat to create selects for each color, and employed ng-change to call the updatebus function, passing in the color id. However, I am encountering an issue where the color id always returns as undefined.
How can I effectively assign colors to buses using these two arrays? What mistake am I making in my approach?
In my attempt to resolve this issue, I referred to this answer: getting the ng-object selected with ng-change
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8>
<title>Example - combining two arrays</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js></script>
</head>
<body ng-app="selectExample">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colors = [
{name:'black', id:'a'},
{name:'white', id:'b'},
{name:'red', id:'c'},
{name:'blue', id:'d'},
{name:'yellow', id:'e'}
];
$scope.buses = [
{name:'bus 1', colorid:''},
{name:'bus 2', colorid:''}
];
$scope.theBus = $scope.buses[1]; // red
$scope.updatebus = function(bus, id){
//alert(id); // undefined
$scope.theBus = bus;
bus.cid = id;
};
}]);
</script>
<div ng-controller="ExampleController">
<p>
Bus Color:
<div ng-repeat="bus in buses">
{{bus.name}}
<select ng-model="myColor"
ng-options="color.name for color in colors"
ng-change="updatebus(bus, color.id)">
<option value="">-- choose color --</option>
</select>
<p>
</div>
<div>
the bus "{{theBus.name}}" has color id "{{theBus.colorid}}"
</div>
</div>
</body>
</html>