AngularJs - 通过将所选对象的列表绑定到所有对象的列表来选择复选框

时间:2017-12-29 21:04:15

标签: angularjs checkbox

我已经搜索了我的问题的解决方案,但未能找到正确的答案 我有所有问题列表和所选问题列表。我需要从所有问题列表中构建一个复选框列表,并检查所选问题列表中的复选框。当对复选框进行更改时,我需要相应更新所选问题的列表。所有问题的清单永远不会改变。我怎么能做到这一点?这是我的情况的缩写版本:



        var MyApp = angular.module('MyApp', []);

        MyApp.controller('MyController', ['$scope', function ($scope) {

            $scope.allQuestions = [
                { q_id: 1, q_txt: 'What time is it?', q_sort: 1},
                { q_id: 2, q_txt: 'What is that?', q_sort: 2},
                { q_id: 3, q_txt: 'Who are you?', q_sort: 4},
                { q_id: 4, q_txt: 'What color is that?', q_sort: 3}
            ];

            $scope.selectedQuestions = [
                { q_id: 1, other_prop: 'yyy' },
                { q_id: 4, other_prop: 'zzz' },
            ];
        }]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">

        <div ng-repeat="question in allQuestions"><input type="checkbox" ng-model="x" /> {{ question.q_txt }}</div>

    </div>
&#13;
&#13;
&#13;

在我的应用程序中,列表来自服务器,我希望能够在保存更改时将选定的问题列表作为对象返回给服务器。 我无法找到完成此操作的绑定,或者如何检查正确的复选框。请注意,这两个列表不同,但是将q_id值作为匹配它们的键。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

听起来您不必担心在用户提交表单之前选择了哪些问题,因此我只需在当时循环查看所有问题的列表并创建一系列所选问题。< / p>

这样的事情:

function getSelections() {
    var selectedQuestions = []
    $scope.allQuestions.forEach( function(question) {
        if (question.selected) {
            var questionCopy = angular.copy(question)
            selectedQuestions.push(questionCopy)
        }
    })
    return selectedQuestions
}

然后在发布之前调用此函数并将结果传递给API。

您应该能够使用ng-model来预先选择应该预先选中的复选框:

<div ng-repeat="question in allQuestions"><input type="checkbox" ng-model="question.selected" /> {{ question.q_txt }}</div>

答案 1 :(得分:0)

这样的事情应该可以解决问题。使用array.find()可能更有效。使用像_这样的库会使这更容易。

   $scope.selectedQuestions.map( function(selectedQuestion) {
        var match = $scope.allQuestions.some( function(question) {
             if (question.q_id == selectedQuestion.q_id) {
                 question.selected = true
                 return true 
             }
             return false
        }
    }