How can AngularJS be used to automatically check a checkbox based on a value in one array, and simultaneously update another array with the checked value or remove it if

enter image description hereHere is a brief overview of the HTML code: I aim to display options from an array within a set object while ensuring that checkboxes are checked for the answers present in another answer array. Furthermore, new answers should be added when more options are selected and removed if unchecked using checkboxes.

<script>

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

adminApp.controller('EditController', function ($scope) {

   
     $scope.viewQuestions=function(){

   set={};  // Assume this object contains answer and option arrays;
 
  var answer= ["answer1", "answer2"]; // Assume array of answers
 
  var options=["option1,option2,option3,option4"]; // Assume array of options
  
  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>

Answer №1

While this may not be exactly what you were looking for, it offers a different approach. I have reimagined the concept to achieve the same result in a more streamlined and angular style, at least in my opinion.

The process involves an array of objects where each object contains the option title (name) and whether it is active or not (active). After every change, the set is updated using filter and map methods, ensuring that it remains current.

(If an array of strings is provided as options, it is assumed that all of them are set to Active: false)

This solution might suit your needs overall, or perhaps it could inspire new ideas based on the code provided.

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

Answer №2

Using angular, you have the ability to bind a checkbox's checked property to a method that retrieves ids from your mini_array contained within the main_array;

---your.html---

enter code here
enter code h
<div class="mb-2"><b>List of Permissions</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);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fixing 500 (Internal Server Error) in Vue.js and Laravel: The Ultimate Guide

Working on a university project using Vue.js and Laravel, I need assistance with sending information to the API. I'm trying to use axios for the POST request, but it's giving me an error: 500 (Internal Server Error). I can't seem to identif ...

Issue encountered with react-toolbox 2.0-beta.6's ThemeProvider not functioning as expected

I have been attempting to modify the color-primary and color-accent variables in react-toolbox using react-toolbox-themr, but without success. I have created a simple git repository to showcase this issue. Below is my react-toolbox-themr.config.json: { ...

Unable to eliminate the string "C:fakepath" using JavaScript's replace function and regular expressions

I've been struggling for quite some time with this issue. Let me share a snippet of the code that's causing trouble: jQuery(':file').change(function() { var path = jQuery(this).val(); var filename = path.replace(/C:\\ ...

Display a CSS box continuously

I have a code for a dropdown function that is working smoothly. Now I would like the comment box to show permanently when clicked and close when clicked outside of it. Currently, when I click on the comment, the box shows up but if I try to input a commen ...

Execute a task on Mobile Safari (after a delay)

I'm currently experimenting with HTML5 on Mobile Safari for iOS 6 and I'm curious about executing JavaScript code after a certain amount of time has elapsed. One specific task I am interested in is redirecting to a different page after 60 seconds ...

Using a directive attribute will convert a boolean value to a string

Is it possible to pass a boolean value to my directive without isolating its scope? The directive includes a link function that captures the attribute's value: link: function(scope, element, attrs, ctrl) { scope.myAttributeValue = attrs.myAttri ...

Converting a JSONArray to a String in Java

I am working with a JSONArray that has the following structure: How can I convert this array to a formatted string? If I attempt to use: json.toString(); The resulting string is as follows: ["package.package.ChecklistModels.ChecklistAnswer@405dddd8", ...

Display the text once using ng-repeat only if a certain condition is met

I am trying to display an element only once within ng-repeat. The issue with my code below is that the "Event of today" message is displayed every time an event starts today... This is my current code: <div class="line" ng-repeat="event in events"& ...

Update the class of the appropriate navigation tab when the corresponding div is scrolled into view

After reading similar questions and doing some research on scrollspy, I don't think it will provide the functionality I need. It seems to only support bootstrap style highlighting. If there is more to it that I'm not aware of, please inform me! ...

What is the best way to update the innerHTML of a date input to reflect the current value entered by the user?

Currently, my task involves extracting data from a table by obtaining the innerHTML of each row. The table contains date inputs that can be manually adjusted or generated automatically. However, the innerHTML does not update accordingly. Thus, when exporti ...

What is the process of server-side web scraping?

Is the title clear enough for what I'm trying to convey? It's a bit challenging to explain, but here goes. My goal: I need to verify if multiple engine numbers (from vehicles) are registered with the local transportation authority. The web inter ...

Can jQuery and Google Analytics be loaded together in a single process?

My current setup includes the following: <script src="http://www.google.com/jsapi?key=..." type="text/javascript"></script> <script> //<![CDATA[ google.load('jquery', '1.6'); //]]> </script> &l ...

Experiencing a lack of data within the local storage feature of ReactJS

I'm encountering an issue where, upon clicking the submit button, my local storage remains empty even though I have data in my array of objects. Despite assigning values to the localArray variable using titleDesMap, the data is not being stored in th ...

What is the best way to supply JSON data to the "The Wall" MooTools plugin while feeding?

I came across this amazing plugin called "The Wall" but unfortunately, neither the documentation nor the examples demonstrate how to utilize JSON objects with it. Imagine we have a JSON array like: [ { href : "/my/photo/image1.jpg", title : "Me an ...

How does jquery's removeClass function on a button continue to function smoothly even after an ajax call

Code Snippet: <span class="input-group-text"> <button type="button" class="btn btn-outline-danger btn-sm owner_button owner_check" name="owner_check" > <i class="far fa-check-circle"></i> </button> </span> ...

Dynamically setting a filter variable in AngularJS through an infoWindow

My select box is successfully interacting with the Angular list. The 'citta' field in the select box filters the list when its value changes. ng-model="queryLoc.citta" First, I initialize the variable $scope.queryLoc = { citta: ''}; ...

Allow clicking through the iframe, while still able to interact with its contents

I am facing a challenge of making an iframe click-through, while ensuring that the body of the iframe remains clickable. I have attempted to achieve this using the following code: iframe.style.width = '100%' iframe.style.height = '100%&apos ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

What are the possible reasons for my load function failing intermittently?

I have encountered an issue with my app where sometimes the content is not loaded into a dialog. Most of the time it works perfectly, but occasionally it fails to display the content. Here is the code snippet that I am using: $('#popup_background&apo ...

Moving information from one controller to another, or the process of converting a controller into a service

Is there a way for me to transfer information from one controller to another? Or can I create a service from a controller? Specifically, I am looking to retrieve coordinates and store them in an object along with other variables. When I try to inject depen ...