Angular JS: How to dynamically add and remove checkboxes in ng-repeat?

Currently, I have successfully implemented a Miller column using Angular and Bootstrap.

To view the functionality in action, you can check out the code snippet at this link.

In the second column of my setup, clicking on a word opens up the third column. However, what I want now is for the checkbox to add that specific word to an array of search terms when clicked.

If the checkbox is unchecked, I need to remove that word from the search terms array. Although adding words works fine as shown in the pen, unchecking the box results in the word being added again.

The solution here lies in checking the state of the checkbox so that if it's true, the word will be added, and if false, the word will be removed from the array.

I am struggling with figuring out how to target and check only the checkbox that was clicked.

   <div class="col-xs-3 inner-column">
<div class="panel panel-default">

  <div class="list-group">
    <div class="list-group-item" ng-class="{active: $index === pmt.millercolumn.level1Selected }" ng-repeat="level1 in pmt.millercolumn.level1 track by $index">
     <input type="checkbox" ng-model="activeSearchTerm" ng-change="pmt.change($index)" id="ng-change-example1" />
      <a href="" ng-click="pmt.getSublevel2($index)" >
        {{level1.name}}
        <i class="pull-right fa fa-angle-right fa-lg"></i>
      </a>
    </div>
  </div>
</div>

When the ng-change event takes place on the checkbox, the following function is called:

   _this.change = function (index) {
    var searchTerm = _this.millercolumn.level1[index].name;
    _this.searchTerms.push(searchTerm);
  };

Answer №1

It appears you are approaching this problem with a jquery mindset, focusing on event handling when things change. A more efficient approach would be to link each checkbox to an item in the array, using ng-model such as level1.isSelected. Then, to build your search terms array, utilize scope.$watch and pass true as the 3rd argument for deep watching your array of items. Whenever a checkbox is checked, the watch function will trigger, allowing you to update the search terms array by extracting the selected list item terms.

Answer №2

To make sure your _change function works properly, include this code:

 _this.change = function (index) {
    console.log('Clicked on', _this.millercolumn.level1[index].name);
    var searchTerm = _this.millercolumn.level1[index].name;
    var searchIndex = _this.searchTerms.indexOf(searchTerm);
    if (searchIndex == -1) {   // If new push
       _this.searchTerms.push(searchTerm);
    }
    else {                    // Else remove item
      _this.searchTerms.splice(searchIndex, 1);
    }
    console.log(_this.searchTerms);
  };

Check out a working demo on Codepen: http://codepen.io/krishcdbry/pen/EgKgBv

Answer №3

Instead of executing the code regardless of the checkbox status, consider implementing this alternative:

_this.updateSearchTerm = function (index, isChecked) {
  var termSelected = _this.millercolumn.level1[index].name;
if(isChecked){
    _this.selectedTerms.push(termSelected);
}
if(!isChecked){
 _this.selectedTerms.pop(termSelected);
}
  };

Answer №4

Just to share my approach that proved to be effective:

<input type="checkbox" ng-model="level1.isSelected" ng-change="pmt.change($index, level1)" id="mycb" />

  _this.change = function (index, item) {
    if (item.isSelected) {
      _this.searchTerms.push(item.name);
    } else {
      var termToRemove = item.name;
      for (var i = _this.searchTerms.length - 1; i >= 0; i--) {
        if (_this.searchTerms[i] === termToRemove) {
          _this.searchTerms.splice(i, 1);
        }
      }
    }
  };

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

Implementing the useEffect hook in React to iterate over JSON data and update the state

Having trouble implementing job location filtering ("remote"/"in-person"/"hybrid") for my personal project. As a beginner in programming, I've spent quite some time troubleshooting the fetchLocationData function and passing URLSearchParams. I anticipa ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

Tips for Transferring Values Between Multiple Dropdown Menus with jQuery

Hello there, can anyone guide me on how to transfer selected items from one multiple combo box to another multi-combo box? I would really appreciate it if someone could provide an example for this scenario. <HTML> <HEAD> <TITLE></T ...

Learn how to toggle a specific div by clicking on an image generated from an ngFor loop in Angular version 11

One issue I am facing is that I have multiple sections containing image info and details. When I click on a specific image, the corresponding details should toggle. Everything works fine, however, if I click on another image without closing the previous ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

The scripts within the body tag are failing to load

After trying to embed angular into the body tag, I noticed that nothing is loading up. Upon inspecting the resources panel, I found that only files from the head are present. Moving all the scripts to the head section resolves the issue and everything load ...

What is the most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

Excessive CPU usage caused by a patch in jQuery dealing with regular expressions

Working on a project developed by an unknown individual has presented some challenges. Without any means of contact with this person, I noticed that the browser's CPU consumption spikes significantly upon loading the page. Upon further investigation, ...

Utilizing Angular JS and Web.API to create an Innovative File Management System

Within my setup, I have two projects. The first is a WebAPI project where I handle classes: FileClass for managing files, DirectoryClass for managing directories, and ClassContext that holds lists of both files and directories. In the HomeController, I&apo ...

After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functiona ...

How can I optimize Javascript and CSS that are being used on my website but are not physically hosted on my website?

On my website, I have a plugin called "Contact Us" that was created and is being operated by Dropifi. Lately, I've been working on optimizing my site for SEO/Speed using Google's PageSpeed Insights tool. I enabled compression with GZip for all el ...

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

Styling components using classes in Material-UI

I recently started using material-ui and noticed that it applies inline styles to each component. After running a test with multiple instances of the same component, I realized that there was no CSS-based styling - only repeated inline styles were generate ...

Angular's implementing Controller as an ES6 Class: "The ***Controller argument is invalid; it should be a function but is undefined."

Struggling to create a simple Angular todo application using ES6. Despite the controller being registered correctly, I keep encountering an error related to the title when navigating to the associated state. *Note: App.js referenced in index is the Babel ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

combine a pair of elements simultaneously

I recently developed a nested directive for a multitabbed form, and here is a simplified version: <outer> <inner heading="a" src="'a.html'" active="true"></inner> <inner heading="b" src="'b.html'"></inner ...

Decompressing an array within a function invocation

Is there a method to pass an array's elements as arguments to a function? For instance, in Python I can accomplish this using: user = ["John", "Doe"] def full_name(first_name, last_name): return first_name + last_name Therefore, full_name(*user ...

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Error encountered when serving tiles using Node JS and Leaflet from the same domain

I have been utilizing the script found at: to run my web application that overlays tile layers from: However, for the past two days, I have been experiencing an issue where tiles are being called in places where they were not previously, causing slow til ...