Reputation: 508
I have a select options and a couple of textareas inside an ng-repeat and what I would like to do is, when I select an option from the menu the respective set of textareas show up some information that belongs to what I just selected.
Instead of doing this all of the textareas created with the ng-repeat show the information.
Here's the link to a JSFiddle that may explain better the problem: https://jsfiddle.net/711yvm8g/5/
Here's the HTML code:
<div ng-app="App">
<div ng-controller="Ctrl">
<div ng-repeat="data in carData">
<select ng-model = "carSelected" ng-change = "changeInfo(carSelected)" data-ng-options = "car as car.name for car in cars">
<option value = "">Select car</option>
</select>
<textarea>{{colorData}}</textarea>
<textarea>{{yearData}}</textarea>
</div>
And here's the Javascript code:
angular.module('App', []);
function Ctrl($scope) {
//This carData object was created only to make the ng-repeat show multiple instances of the fields.
$scope.carData = {
a:"abc",
b:"def"
}
$scope.cars = [{
name: "Volvo"
}, {
name: "Saab"
}]
var volvoInfo = {
color:"Blue",
year:"2016"
}
var saabInfo = {
color:"Red",
year:"2015"
}
$scope.changeInfo = function(carSelected) {
if(carSelected.name == "Volvo") {
$scope.colorData = volvoInfo.color;
$scope.yearData = volvoInfo.year;
} else {
$scope.colorData = saabInfo.color;
$scope.yearData = saabInfo.year;
}
}
}
Is there a way I can solve this issue? Thanks a lot.
Upvotes: 1
Views: 422
Reputation: 2519
You should restructure your code to use arrays of objects. That way it is easier to manage.
angular.module('App', []);
function Ctrl($scope) {
let carInfoModel = {
name: '',
color: '',
year: '',
}
$scope.cars = [angular.copy(carInfoModel),angular.copy(carInfoModel)]
$scope.carsInfo = [{
name: 'Volvo',
color: 'Blue',
year: "2016"
}, {
name: 'Saab',
color: 'Red',
year: "2015"
}]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">
<div ng-controller="Ctrl">
<div ng-repeat="data in cars">
<select ng-model="data" data-ng-options="car as car.name for car in carsInfo">
<option value="">Select car</option>
</select>
<textarea>{{data.color}}</textarea>
<textarea>{{data.year}}</textarea>
</div>
</div>
</div>
Upvotes: 1
Reputation: 19212
Try Ctrl.colorData and Ctrl.yearData for your textarea bindings
Upvotes: 0