簡體   English   中英

如何設置基於一個數組中的值選中的復選框並將值添加到另一個數組(如果選中),否則使用angular js刪除?

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

在此處輸入圖像描述以下只是代碼的概述,如html 代碼中所示,我只想顯示來自 set 對象的 options 數組中選項,並且必須將選中的復選框設置為選項,這是來自答案數組的答案,並且必須添加如果我單擊復選框檢查更多選項,則要回答的新答案,如果未選中復選框,則必須刪除答案

 <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>

這不完全是你想要的,但它是一些東西。 我改變了概念,以更簡潔的方式和更有棱角的風格來做同樣的事情。 (在我看來)

我有一個對象數組( name :選項標題和active :是否選中)並且每次更改后我都會更新該集合。 帶過濾器和地圖; 因此,該集合始終是最新的

(如果您收到一個字符串數組作為選項,您可以假設它們都是 Active: false

也許它一般對你有用,或者你可以從代碼中得到一個想法。

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

angular 中,您可以將復選框的 checked 屬性綁定到一個方法該方法返回位於 main_array 中的 mini_array 的 id;

---你的.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>

---你的.ts---

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM