ors*_*zky 5 javascript angularjs angularjs-scope ng-options
我在找出ng-repeat中的作用域时遇到了麻烦.我想创建链式选择,我想让ng-repeat中的每一行分别存在于不同的范围内.当前更改任何行中的第一个选择将更改所有行中的第二个选择.
(现实生活中的例子:我有一个表格,我必须添加汽车,首先选择'制造',从api拉出'模型',然后在第二个选择中显示模型.用户必须能够添加任意数量的汽车.)
HTML:
<div ng-controller="MyCtrl">
<div ng-repeat="row in rows">
<select ng-options="option.value as option.title for option in options1" ng-model="row.select1" ng-change="updateSelect2(row.select1)"></select>
<select ng-options="option.value as option.title for option in options2" ng-model="row.select2"></select>
</div>
<a ng-click="addRow()">Add Row</a>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
function MyCtrl($scope) {
$scope.rows = [{}];
$scope.options1 = [
{title: 'Option 1', value: '1'},
{title: 'Option 2', value: '2'},
{title: 'Option 3', value: '3'}
];
$scope.options2 = [];
$scope.updateSelect2 = function(val) {
if (val === '1') {
$scope.options2 = [
{title: 'A', value: 'A'},
{title: 'B', value: 'B'}
];
} else if (val === '2') {
$scope.options2 = [
{title: 'AA', value: 'AA'},
{title: 'BB', value: 'BB'}
];
} else {
$scope.options2 = [
{title: 'AAA', value: 'AAA'},
{title: 'BBB', value: 'BBB'}
];
}
};
$scope.addRow = function() {
$scope.rows.push({});
};
}
Run Code Online (Sandbox Code Playgroud)
您需要将options2每一行的部分分开。
一个简单的解决方案是将其保存在行对象内,但您可能需要更复杂的数据结构。
这是一个使用您的代码的简单示例。
HTML:
<div ng-repeat="row in rows">
<select ng-options="option.value as option.title for option in options1" ng-model="row.select1" ng-change="updateSelect2(row.select1, $index)"> </select>
<select ng-options="option.value as option.title for option in row.options2" ng-model="row.select2"></select>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
$scope.updateSelect2 = function(val, index) {
if (val === '1') {
$scope.rows[index].options2 = [
{title: 'A', value: 'A'},
{title: 'B', value: 'B'}
];
} else if (val === '2') {
$scope.rows[index].options2 = [
{title: 'AA', value: 'AA'},
{title: 'BB', value: 'BB'}
];
} else {
$scope.rows[index].options2 = [
{title: 'AAA', value: 'AAA'},
{title: 'BBB', value: 'BBB'}
];
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |