我有一个ng-repeat
- ed表格行,里面是一对有角度的select
s:
<div ng-controller="midiCtrl" id="midi-ctrl">
[...]
<tr ng-repeat="plugin in plugins">
<td><strong>{{plugin.name}}</strong></td>
<td>
<select class="span1" ng-model="selectedChannel" ng-options="item.ID as item.Title for item in channels">
</td>
<td>
<select class="span2" ng-model="selectedDevice" ng-options="item.ID as item.Title for item in devices">
</td>
</tr>
[...]
</div>
控制器是:
app.controller('midiCtrl', function ($scope, pluginDisplayedWindows) {
$scope.plugins = pluginDisplayedWindows.pluginsDisplayed; // An object
$scope.channels = [
{ID: 'all', Title: 'All'},
{ID: '0', Title: '1'},
{ID: '1', Title: '2'},
{ID: '2', Title: '3'}
];
$scope.devices = [
{ID: '0', Title: 'Device A'},
{ID: '1', Title: 'Device B'},
{ID: '2', Title: 'Device C'},
{ID: '3', Title: 'Device D'},
];
});
现在,我知道当选择其中一个选择时,相应的对象在ng-model范围变量($scope.selectedChannel
或$scope.selectedDevice
)上设置,但显然它设置为 在相应的ng-repeat子范围 。
如何在控制器中访问子范围?我想在用户按下按钮时保存所有选择,但如果我尝试在midiCtrl
控制器中执行此操作,则无法访问由ng-repeat
创建的子范围。
答案 0 :(得分:3)
最简单的技巧是将所选值添加到当前plugin
对象,这样您就可以轻松获取所选值,并且这些值自然地绑定到正确的plugin
对象。不会引入其他对象。非常简单。
<select class="span1" ng-model="plugin.selectedChannel" ng-options="item.ID as item.Title for item in channels">
<select class="span2" ng-model="plugin.selectedDevice" ng-options="item.ID as item.Title for item in devices">
的 Working Demo 1 强>
如果您想单独存储,可以
<select class="span1" ng-model="selected[$index].selectedChannel" ng-options="item.ID as item.Title for item in channels" />
<select class="span2" ng-model="selected[$index].selectedDevice" ng-options="item.ID as item.Title for item in devices" />
$scope.selected = [];
angular.forEach($scope.plugins, function (a) {
$scope.selected.push({
selectedChannel: undefined,
selectedDevice: undefined
});
})
的 Working Demo 2 强>
答案 1 :(得分:2)
您可以先在父控制器中定义所选对象。你数据绑定的对象应该总是“有一个点”,以避免原型继承问题,所以你应该绑定到像“selected.channel”而不是“selectedChannel”
app.controller('midiCtrl', function ($scope, pluginDisplayedWindows) {
$scope.plugins = pluginDisplayedWindows.pluginsDisplayed; // An object
$scope.selected = {};
$scope.selected.channel = {};
$scope.selected.device = {};
$scope.channels = [
{ID: 'all', Title: 'All'},
{ID: '0', Title: '1'},
{ID: '1', Title: '2'},
{ID: '2', Title: '3'}
];
$scope.devices = [
{ID: '0', Title: 'Device A'},
{ID: '1', Title: 'Device B'},
{ID: '2', Title: 'Device C'},
{ID: '3', Title: 'Device D'},
];
});
并相应地更新HTML
<div ng-controller="midiCtrl" id="midi-ctrl">
[...]
<tr ng-repeat="plugin in plugins">
<td><strong>{{plugin.name}}</strong></td>
<td>
<select class="span1" ng-model="selected.channel" ng-options="item.ID as item.Title for item in channels">
</td>
<td>
<select class="span2" ng-model="selected.device" ng-options="item.ID as item.Title for item in devices">
</td>
</tr>
[...]
</div>