jeudi 29 janvier 2015

How to use AngularJS to update an object array based on a selection change


I have two dynamic object arrays. One for colors, one for buses. The goal is to assign a color to a bus. So, using ng-repeat the code create selects for each color, then using ng-change to call a the updatebus function, passing in the color id. But, it doesn't work. The color id is always undefined.


How can I assign the color to the bus with two arrays? What am I doing wrong?


I tried looking at this answer: getting the ng-object selected with ng-change


Plunker



<!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>




Aucun commentaire:

Enregistrer un commentaire