简体   繁体   中英

how to set checkbox checked based on value in one array and add value to another array if checked otherwise remove using angular js?

enter image description here Following is just the overview of the code,as given in html code i just want to show the options from options array from set object and have to set checkbox checked to option which is an answer from answer array and have to add new answer to answer if i check more options with checkbox clicked, and have to remove answer if checkbox is unchecked .

 <script> var adminApp = angular.module('app',[]); adminApp.controller('EditController', function ($scope) { $scope.viewQuestions=function(){ set={}; //object in which answer array and option array is present //assume; var answer= ["answer1", "answer2"]; //answer array assume var options=["option1,option2,option3,option4"]; //option array assume var answerType="Multiple"; } $scope.updateAnswer =function(isSet,index,answer,set) { for(var i=0;i<set.answer.length;i++) { if(isSet===set.answer[i]) { set.answer[index]=isSet; } else { set.answer.splice(index, 1); } } } } </script>
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script> </head> <body ng-app="app" ng-controller="EditController" ng-init="viewQuestions()"> <table> <tr> <td ng-show="s.answerType === 'Multiple'"> <p ng-repeat="o in s.options">{{$index + 1}}. <input type="checkbox" name="answer-{{index}}" ng-model="isSet" value="{{o}}" ng-change="updateAnswer(isSet,$index,answer,s)">{{o}}</p> </td> </tr> </table> </body> </html>

This is not exactly what you want but it's something. I change the concept to do the same in a cleaner way and more angular style. (in my opinion)

I have an array of objects ( name : The option title & active : Checked or not) And after each change I update the set. With filter & map; So, the set is always up to date

(If you receive a array of string as options, you can assume that all of them are Active: false )

Maybe it can works for you in general, or you can get an idea from the code.

http://plnkr.co/edit/GucWDwF66A56IkXHHpwG?p=preview

In angular , you can bind checkbox's checked property to a method that returns ids of your mini_array that is in main_array;

---your.html---

enter code here
enter code h
<div class="mb-2"><b>Permissions list</b></div>
<div formArrayName="permissions" *ngFor="let permission of main_array; let i=index">
<input class="mr-2" [checked]="isChecked(permission.id)" type="checkbox">
    {{permission.name}}
</div>

---your.ts---

  isChecked(id) {
    return this.mini_array.includes(id);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM