我有一个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
创建的子范围。
最简单的技巧是将所选值添加到当前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">
工作演示 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
});
})
工作演示 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>