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

What is the best way to determine the total number of elements within this JSON data structure?

Is there a way to determine the number of elements in a JSON object using JavaScript? data = { name_data: { 35: { name: "AA", }, 47: { name: "BB", }, 48: { name: "CC", ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

The selected attribute does not function properly with the <option> tag in Angular

Currently, I am faced with a challenge involving dropdowns and select2. My task is to edit a product, which includes selecting a category that corresponds to the product. However, when I open the modal, the selected group/category is not displayed in the d ...

Encountered the error message "A property 'split' cannot be read of undefined" while attempting to run a React Native application

I was able to run a react-native app without any issues yesterday, but today when I tried to run it again, I encountered some problems. After running "npm start" to start metro, I then attempted to run "npx react-native run-android". However, I received th ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

javascript - The Key Pair of a Jquery Object is Not Defined

I'm currently going through an HTML element, which is an input field using jQuery, but I keep encountering an error. Here's the code snippet: $(".submit_button").on("click touch", function(e){ e.preventDefault(); var formdat ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

The Javascript code I wrote is unable to detect the array element that was initially defined in Python

Trying to launch a new browser window through Selenium using driver.execute_script("window.open('');") However, the goal is to open a specific link provided by the user. For this purpose, extracted the link input from an array and inc ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Is there a messaging app that provides real-time updates for when messages are posted?

I am in the process of developing a messaging application. User1 sends out a message, and I want to display how long ago this message was posted to other users - for example, "Posted 9 min. ago", similar to what we see on sites like SO or Facebook. To ach ...

How to Generate an Array of JSON Objects in JavaScript on a Razor Page using a Custom ViewModel in MVC?

Attempting to populate the array within my script for future charting with D3.JS, I came across some issues. Following advice from this post, I used a specific syntax that unfortunately resulted in an error stating "Uncaught ReferenceError: WebSite is not ...

Iterating variables in Vue.js is reminiscent of the process in AngularJS

When working on my application using vue.js, I am interested in finding the last repeated element within a v-for directive. I understand that in angularjs, there is a similar concept using the $last loop variable in its ngRepeat directive: <div ng-repe ...

Is it possible for me to retrieve/load a <datalist> element from a different file?

I'm in the process of developing a Google Chrome extension that essentially consists of a dropdown menu and an input box with datalists. The user can change their selection in the dropdown menu, which will then switch the datalist being used by the in ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head." I have successfully implemented the show/hide functionalit ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

The designated <input type=“text” maxlength=“4”> field must not include commas or periods when determining the character limit

In the input field, there are numbers and special characters like commas and dots. When calculating the maxLength of the field, I want to ignore special characters. I do not want to restrict special characters. The expected output should be: 1,234 (Total ...

Creating a dynamic select input in React that displays a default value based on other user inputs

My dilemma involves working with two radio buttons, named radio1 and radio2, along with a select input. The options available in the select input are conditional based on the selected radio button. I am aiming to automatically set the value of the select t ...