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

Conceal the information within a table using angular js and HTML

Just starting out with angular and I have a table that displays angular data directly in the HTML without any controller or model. <table width="98%" border="0" cellspacing="1" cellpadding="2" class="labels" align="center" id="locc"> <tr style ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...

What are the techniques for integrating PHP code into JavaScript/Ajax?

I am curious about how to integrate PHP code into JavaScript/Ajax. Here is the PHP code I am working with: if ($folder = opendir('data/Tasklist/')) { while (false !== ($file = readdir($folder))) { if ($file != '.' && $ ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Inconsistency in handling express routes results in empty req.body in certain routes

I have two different paths to follow. Before each request, a method needs to be executed: app.all('*',function(req,res,next){ console.dir(req.body); // Additional operations }); When I send a POST request to my first path: $http.post ...

Employing eval for parsing the JSON data

function ajaxFunction(){ var ajaxRequest; // The variable that enables the use of Ajax technology! try{ // Compatible with Opera 8.0+, Firefox, and Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Explorer Browsers ...

Generating Bootstrap Vue Dropdown components in real time

I am currently utilizing Bootstrap Vue to construct a dynamic Dropdown component that can render different elements such as item, title, and divider. Is there a method to accomplish this task effectively? The desired outcome for the Dropdown component wou ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

The useEffect function is executing two times

Check out this code snippet: import { type AppType } from 'next/app' import { api } from '~/utils/api' import '~/styles/globals.css' import Nav from '~/components/Nav' import { useEffect, useState } from 'react& ...

Incorrect interpretation of JavaScript object

To display some structured data on my JADE page, I created a JSON-like object containing variables, text, and JavaScript objects. Here is an example of what the JSON object looks like: var dataSet1 = { meta: { "name": "Some text", "minimum": mini_ ...

How can I manage the transfer of items between lists in angular-ui sortable?

I am currently utilizing angular-ui sortable version 1.2 My goal is to manage the transfer of an item from one list to another and ensure that the back-end gets updated accordingly. The jquery-ui-sortable plugin offers various events, such as the receive ...

Having trouble assigning a value to the datapicker through the onchange event and the name attribute in the code below

const stateValues = { code: '', product: '', checked: 'false', jobCardNo: '', openDate: '', completionDate: '', serial: '', technicalNo: '', ...

Issue with loading CSS and JavaScript following a GET request

I initially used express and the render function to display different pages on my website. However, I've now decided to switch to vanilla JavaScript instead. The objective is to load the HTML file along with all the necessary JS and CSS files. Below i ...

Retrieving multiple lines of text from the database and populating a TextArea

I am encountering an issue with multi line text saved in a MySql database as VARCHAR 255. When I retrieve and process it using the nl2br PHP function, it displays correctly (with multiple lines). However, when I retrieve the multi line text from the databa ...

Having trouble storing data in a MYSQL database with NodeJS and ReactJS

When trying to submit the form, a "Query Error" popup appears and data is not being saved in the database. API router.post("/add_customer", (req, res) => { const sql = `INSERT INTO customer (name, mobile, email, address, state, city, policytype, insu ...

Retrieve data from ngModel within a custom directive

I'm attempting to retrieve the value of ngModel from my input by utilizing a directive, sadly I'm having difficulty retrieving it. Take a look at my code: angular .module('myapp') .directive('infoVal', myExtractor); ...

The jqGrid is not showing the AJAX JSON data as expected

Currently, I am exploring jqgrid and trying to figure out how to display data in another jqgrid when clicking on a specific colmodel. The retrieved data from the server goes through a function and reaches the grid, but no information is displayed without a ...

What strategies can I employ to address this historical issue?

Encountered TypeError: (0 , history_history__WEBPACK_IMPORTED_MODULE_6_.default) is not a function This issue arises in my history.js file import { createBrowserHistory } from 'history'; export default createBrowserHistory({ forceRefresh: tr ...

Pass an item along with its superclass using express

Is there a way to send an object from an express server and then check the instanceof of that object on the receiving end? I am working on integration tests for express and need to verify the instanceof of the response body. Unfortunately, it seems like t ...