如何在ng-repeat指令中为多个选择添加动态选项
给定一个包含一些选项元素的HTML文档,任务是在angularJS中使用ng-repeat动态地添加一个有多个选择的javascript对象数组。
方法:任务是使用ng-repeat完成的,它在一个数组中循环。让我们把这个数组称为“models “。DOM中的每个选择菜单都被建模为数组中的特定索引。例如,第2个选择菜单将被建模为模型的对象数组中的第2个对象。为了在DOM中添加更多的选择菜单,我们只需要向模型的数组中推送一个空对象,ng-repeat指令会处理其余的复制工作。
例子1:在这个例子中,我们将添加多个选择并显示所选数据。
<!DOCTYPE html>
<html ng-app="gfg">
<head>
<meta charset="utf-8" />
<script data-require="angular.js@1.5.x"
src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"
data-semver="1.5.11">
</script>
<script>
var app = angular.module('gfg', []);
app.controller('MainCtrl', function(scope) {
scope.models = [{}];
scope.countries = ['India', 'Japan', 'US'];
scope.states = {
India: ['UP', 'MP', 'Bihar'],
Japan: ['Tokyo', 'Yokohama'],
US: ['California', 'Texas'],
}
scope.addRow = function() {
scope.models.push({});
}
scope.getState = function(country) {
returnscope.states[country];
}
});
</script>
</head>
<body ng-controller="MainCtrl">
<center>
<h1 style="color: green;">
GeeksForGeeks
</h1>
<table>
<tr>
<th>Country</th>
<th>State</th>
<th>Action</th>
</tr>
<tr ng-repeat="model in models">
<td>
<select ng-options=
"country as country for country in countries"
ng-model="model.country"
ng-change='getState(model.country)'>
</td>
<td>
<select ng-options=
"state as state for state in getState(model.country)"
ng-model="model.state">
</td>
<td>
<button ng-click="addRow()">Add Row</button>
</td>
</tr>
</table>
<h3 style="color:green">Selections</h3>
<p ng-repeat="model in models">
{{model.country}} - {{model.state}}
</p>
</center>
</body>
</html>
输出:所有的数据都被成功添加到对象数组中。
例子2:在这个例子中,我们预先填充了模型数组。
<!DOCTYPE html>
<html ng-app="gfg">
<head>
<meta charset="utf-8" />
<script data-require="angular.js@1.5.x"
src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"
data-semver="1.5.11">
</script>
<script>
var app = angular.module('gfg', []);
// Prepopulate the models array here
app.controller('MainCtrl', function(scope) {
scope.models = [{
country: 'India',
state: 'UP'
}];
scope.countries = ['India', 'Japan', 'US'];
scope.states = {
India: ['UP', 'MP', 'Bihar'],
Japan: ['Tokyo', 'Yokohama'],
US: ['California', 'Texas'],
}
scope.addRow = function() {
scope.models.push({});
}
scope.getState = function(country) {
returnscope.states[country];
}
});
</script>
</head>
<body ng-controller="MainCtrl">
<center>
<h1 style="color: green;">
GeeksForGeeks
</h1>
<table>
<tr>
<th>Country</th>
<th>State</th>
<th>Action</th>
</tr>
<tr ng-repeat="model in models">
<td>
<select ng-options=
"country as country for country in countries"
ng-model="model.country"
ng-change='getState(model.country)'>
</td>
<td>
<select ng-options=
"state as state for state in getState(model.country)"
ng-model="model.state">
</td>
<td>
<button ng-click="addRow()">Add Row</button>
</td>
</tr>
</table>
<h3 style="color:green">Selections</h3>
<p ng-repeat="model in models">
{{model.country}} - {{model.state}}
</p>
</center>
</body>
</html>
输出:我们看到该页面现在总是包含国家 “印度 “和州 “UP”,因为它在页面加载时预填了。