编程语言
首页 > 编程语言> > javascript – ng-repeat指令中的角度选择:如何访问子范围?

javascript – ng-repeat指令中的角度选择:如何访问子范围?

作者:互联网

我有一个ng-repeat-ed表格行,里面有一对角度选择:

    <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创建的子范围.

解决方法:

最简单的技巧是将所选值添加到当前插件对象,这样您就可以轻松获取所选值,并且这些值自然地绑定到正确的插件对象.不会引入其他对象.非常简单.

<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

标签:angularjs-select2,javascript,angularjs,angularjs-scope,angularjs-ng-repeat
来源: https://codeday.me/bug/20190831/1776569.html