我在ng-repeat中有一个选择选项和几个textareas,我想要做的是,当我从菜单中选择一个选项时,相应的textareas集显示了一些属于我刚才的信息地选择。
使用ng-repeat创建的所有textareas都显示信息,而不是这样做。
这里是JSFiddle的链接,可以更好地解释问题: https://jsfiddle.net/711yvm8g/5/
这是HTML代码:
<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>
以下是Javascript代码:
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;
}
}
}
有没有办法可以解决这个问题?非常感谢。
答案 0 :(得分:1)
您应该重构代码以使用对象数组。这样就更容易管理了。
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>
答案 1 :(得分:0)
尝试使用Ctrl.colorData和Ctrl.yearData作为textarea绑定