How to programmatically unselect an ng-checkbox in AngularJS when it is removed from an array

Utilizing checkboxes to gather values and store them in an array for dataset filtering purposes.

The objectives are as follows:

  1. Show child filters when parent category is selected.

  2. Unselect all children if parent is unselected (otherwise they will remain hidden but still selected)

  3. Display active filters

  4. Remove active filter on click (also uncheck corresponding checkbox programmatically).

  5. Clear all filters and uncheck all checkboxes.

Present code provided below, see attached fiddle for more information.

$scope.IsChecked = false;
$scope.ActiveFilters = [];

$scope.clearFilters = function() {
    $scope.ActiveFilters = [];
};

$scope.ModifyFilter = function (IsChecked, Filter) {
    console.log(IsChecked);
  if (IsChecked) {
    $scope.ActiveFilters.push(Filter);
  }
  else {
    var indexz = $scope.ActiveFilters.indexOf(Filter);
    $scope.ActiveFilters.splice(indexz, 1);
  }
};

For a partially functional demo, check out the Fiddle here

-- EDIT --

Extra clarification: If a checkbox value is removed from the 'Active Filters' section by clicking on its name at the bottom of the fiddle, it does not result in unchecking the checkbox. The same issue occurs when using 'Clear Filters'.

Answer №1

The issue lies within your html bindings. Please share the code here so we can take a look. You are using the "IsChecked" variable, which is a local scope variable created for each iteration of the loop. You are not updating it in your script code.

Here is the updated html:

<body ng-app="DemoApp" ng-controller="DashboardCtrl"> 

    <div ng-repeat="group in Filters">

       <input type="checkbox" value="{{group.title}}" ng-model="CheckboxParent" />
           {{group.title}}

       <div ng-show="CheckboxParent" class="animate-show" ng-repeat="filter in group.filters">

           <input type="checkbox" class="filterChild" value="{{filter.name}}" ng-model="filter.checked" ng-change="ModifyFilter(filter.checked,filter)"/>
                {{filter.name}} 
       </div>
    </div>

    <div>
      <h4>Active Filters</h4>

        <p class="clear-filters" ng-click="clearFilters()">Clear Filters</p>
        <ul ng-repeat="activeFilter in ActiveFilters">
            <li ng-model="activeFilter.checked" ng-click="removeFilter(ModifyFilter(activeFilter.checked,activeFilter))">{{activeFilter.name}}</li>
        </ul>
    </div>

</body>

Updated script:

var app = angular.module("DemoApp", [])

app.controller("DashboardCtrl", function($scope) {

    $scope.clearFilters = function() {
        angular.forEach($scope.Filters[0].filters, function(filter) {
          filter.checked = false;
        });
        $scope.ActiveFilters = [];
    };

    $scope.IsChecked = false;
    $scope.ActiveFilters = [];

    $scope.ModifyFilter = function (IsChecked, Filter) {
        console.log(IsChecked);
      if (IsChecked) {
        $scope.ActiveFilters.push(Filter);
      }
      else {
        var indexz = $scope.ActiveFilters.indexOf(Filter);
        $scope.ActiveFilters.splice(indexz, 1);
      }
    };


    $scope.Filters = 
         [
        {
            "title": "Equipment",
            "filters": [
                { name: "Rope", checked: false },
                { name: "Cables", checked: false },
                { name: "Dowel", checked: false },
                { name: "Ball", checked: false }
            ]
        }
    ];  
});

You can find my solution on js fiddle: JsFiddle

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

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

Verify the text file for any data, and if it contains any, display it on the web browser using JavaScript

I have a program in C that works with a temperature sensor. It creates a file to store the temperature and indicates whether it falls within specific values. I want to display this data on a web browser and update it every 5 minutes. I'm looking for ...

An issue has occurred with the HTTP request to a PHP file in Angular

When attempting to send an http request to my php file, I encountered the following error message Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":" ...

Utilizing the Express-busboy npm package to generate a new directory within the public folder of

While working on my controller, I encountered an issue when trying to readFile sent from the browser via AJAX. Unexpectedly, a directory was created in my public folder with a name like '3d6c3049-839b-40ce-9aa3-b76f08bf140b' -> file -> myfile ...

Tips for linking together AJAX requests with vanilla JavaScript

I have searched extensively for solutions using only plain JavaScript, but I have not been able to find a suitable answer. How can I tackle this issue with pure JavaScript given that my repetitive attempts haven't yielded any results? function ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

After props have been passed, the ReactJS ComponentWillMount() function is triggered

Can anyone explain why the child component is only rendered once, even though I pass props to it every time I click a button? Whenever I click a button that passes props to the child, the ComponentWillMount() method of the child component doesn't tri ...

standards for matching patterns (such as .gitignore)

Throughout my experience, I have utilized various tools designed to search a codebase for specific files and then carry out operations on those files. One example is test libraries that identify all the necessary files for execution. Another common tool is ...

Simple request results in an error

I have been experimenting with the Electrolyte dependency injection library, but I am encountering an error even when trying a simple script that requires it. I haven't come across any discussions or problems similar to mine in relation to this issue ...

How to send a contact form in Wordpress with multiple attachments via email without using any plugins

The main objective is to enable users to submit their own content for new articles (including text and files) to the administrator's email. A form has been created for this purpose: <form class="form form-send" enctype="multipart/fo ...

Tips on designing checkboxes with CSS

Can someone help me figure out how to style a checkbox using the code below? <input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" /> I've tried applying this style but it doesn't seem to work. The chec ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.usercount; columnDefs: [{ nam ...

What is the best way to extract values from this PHP script?

I recently delved into the d3 javascript library and successfully created a scatter plot chart that pulls random values from an array. Below is the code snippet: <!DOCTYPE html> <meta charset="utf-8"> <head> <script type="text/ja ...

What is the method of utilizing shared services when the controllers do not rely on any shared services?

Let's imagine a scenario where there is a module containing only one factory, which serves as the shared service. angular.module('sharedService', []) .factory('sharedSrv', sharedService) function sharedService() { var numbe ...

Retrieve the red, green, and blue components of a color in the RGB format

When I retrieve "rgb(18, 115, 224)" from a DOM element, I need to convert this color to hexadecimal in order to assign it to a span element. To get the hexadecimal equivalent of the color, I can use the following code snippet: "#" + componentToHex(r) + co ...

Unusual behavior observed while looping through an HTMLCollection returned by the getElementsByClassName method

After spending some time debugging, I discovered an issue with my function that changes the class of elements to modify their properties. Surprisingly, only specific elements were being affected by this change. It took me a while to troubleshoot and resolv ...

"Troubleshooting async/await issue with Node.js Sequelize and configuring the connection

function credential(secretFromVault) { const creddetails = new ClientSecretCredential(clientId, tenantId, clientSecret); // Build the URL to reach your key vault const url = `https://<vaultName>.vault.azure.net/`; // Lastly, create our secre ...

Issue with adding to lightbox feature when loading content dynamically using AJAX PHP is not functioning as expected

Hey there! I've encountered an interesting issue with my code that adds models to a lightbox. It's functioning perfectly on static pages like this one. $scope.add = function(permalink, post_id) { if (typeof(Storage) !== "undefined") { ...