vendredi 29 décembre 2017

AngularJs - Select checkboxes by binding list of selected objects to list of all objects

I have searched for a solution to my problem but have not been able to find the right answer.
I have a list of all questions and a list of selected questions. I need to build a list of checkboxes from the list of all questions and check the ones that are in the list of selected questions. When changes are made to the checkboxes, I need the list of selected questions to be updated accordingly. The list of all questions never changes. How can I accomplish this? Here's a very abbreviated version of my situation:

        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, selected: false },
                { q_id: 2, q_txt: 'What is that?', q_sort: 2, selected: false },
                { q_id: 3, q_txt: 'Who are you?', q_sort: 4, selected: false },
                { q_id: 4, q_txt: 'What color is that?', q_sort: 3, selected: false }
            ];

            $scope.selectedQuestions = [
                { q_id: 1, other_prop: 'yyy' },
                { q_id: 4, other_prop: 'zzz' },
            ];
        }]);
<script src="http://ift.tt/1mQ03rn"></script>
<div ng-app="MyApp" ng-controller="MyController">

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

    </div>

In my application the lists come from a server and I would like to be able to return the selected questions list as an object back to the server when saving the changes. I can't figure out the binding to accomplish this, or how to check the right checkboxes. Notice that the two lists are different, but bothe have the q_id value as the key to match them. Any help would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire