Angular: utilizing a ng-false-value function

Within my Angular application, I have a series of checkboxes generated using a nested ng-repeat:

<div ng-repeat="partner in type.partners">
    <label class="checkbox-inline">
        <input type="checkbox"
        ng-model="partners[$parent.$index][$index]"
        ng-true-value="{{partner}}"
        ng-change="handleCheckboxChanged({{type.id}})"
        ng-checked="getChecked({{partner.id}})"
        >
        <p><span ></span>{{partner.name}}<p>
    </label>
</div>

The resulting layout is illustrated below:

https://i.sstatic.net/CovX4.png

Upon selecting a partner through a checkbox, it joins the list of selected partners utilizing ng-true-value and ng-model.

If a user decides to unselect a partner by unticking the checkbox, the object still retains the key:value pair with a value of false, as shown in the console here:

https://i.sstatic.net/3Ajf5.png

I would prefer for this key:value pair to be removed entirely upon unchecking a checkbox, rather than simply changing its value to false.

Is there a way to achieve this by utilizing a function as the ng-false-value trigger?

Answer №1

Your explanation indicates a default behavior that can be customized through your ngChange function.

Here's a straightforward illustration of how you can achieve the desired outcome.

<div ng-repeat="partner in partners">
    <label>
        <input type="checkbox"
        value="partner.id"
        ng-model="partner.selected"
        ng-change="changeValue(partner)"
        />
        {{partner.name}}
    </label>
</div>

var partnersList = [], idsArray = [];

$scope.changeValue = function(partner){
   if(partner.selected)
      addPartner(partner);
   else
      removePartner(partner);
};

var addPartner= function(partner){
    if(!existInList(partner))
       partnersList.push(partner);
};

var removePartner= function(partner){
    idsArray = getIdsArray();
    var indexToRemove = idsArray.indexOf(partner.id);
    if(indexToRemove == -1)
       return;

    partnersList.splice(indexToRemove, 1);
};

var existInList = function(partner){
    idsArray = getIdsArray();
    return idsArray.indexOf(partner.id) != -1;
};

var getIdsArray = function(){
    return partnersList.map(function(partner){ return partner.id });
};

Check out this JSFiddle demo for reference.

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

The state is not being configured accurately

In my ReactJs project, I have a model Component with a picture that is displayed. I want to pass the data of the clicked picture, which can be neither raw data nor a URL. I have implemented a handler that can delete the picture (if pressed with the Ctrl k ...

Ways to combine X and Y velocities into a single velocity

Is there a way to combine the X and Y Velocity into a single Velocity without considering the angle? var velocityX = some value; var velocityY = some value; // Need to convert both X and Y velocities into one combined velocity ...

Stop the default behavior of a link based on the Ajax response

A controller has been created in Magento to check if there are any products in a list. If products exist in the list, it will return true; otherwise, it will return false. The front-end below triggers an ajax call. It must remain a link and cannot be chan ...

Protractor and Azure AD authentication test in action

I am having trouble authenticating a user with an end-to-end test. Despite clicking the button on the Azure AD login page, the test does not proceed as expected. describe('angularjs homepage', function() { var ptor = protractor.getInstance(); p ...

Is there a way to execute this process twice without duplicating the code and manually adjusting the variables?

I'm looking to modify this code so that it can be used for multiple calendars simultaneously. For example, I want something similar to the following: Here is what I currently have: This is my JavaScript code: var Calendar = { start: function () ...

The craft of masonry is known for its creation of intentional gaps

I've gone through all the posts related to this issue, but none of the suggested solutions seem to work for me. Here is a visual representation of my grid: https://i.sstatic.net/ybufk.png If you want to see the code and play around with it, check o ...

Steps for choosing all choices in a multi-select menu without changing the order

What is the best way to choose all the options from a multiselect box using Java Script? ...

Combining ApolloProvider and StatsigProvider in ReactJs: A Step-by-Step Guide

Currently in my React (Next.js) application, I am utilizing statsig-react to switch between mastergraphql endpoint URLs. However, I am encountering an issue when trying to connect statsig with Apollo. This is how my app.js file looks like: const apollo = ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

How can we process the incoming data that is in a JSON format?

I'm in the process of creating a Zap that collects customer feedback through Unbird and delivers a coherent Slack message that can be easily understood by anyone within my organization. When importing customer feedback data from Unbird into Zapier, i ...

Deactivate a dropdown option in Angular's uib-dropdown

Currently in my angular template, I am working on a dropdown menu using angular-ui. The requirement is to disable certain list items based on a property of the "company" object defined in the ng-repeat. I've already experimented with the disabled tag ...

Moment-Timezone defaults to the locale settings after the global Moment locale has been established

I am currently developing an application using Typescript that requires features from both Moment.js and moment-timezone. To localize the date and timestamps within the application, I have set moment's locale in the main app.ts file to match the langu ...

Integrate NodeJs into Ionic framework for enhanced functionality and dynamic

I created a hybrid application using Ionic framework. Currently, I have been using PHP and MySQL as the backend technology. However, after doing some research, I realized that Node.js with Express.js and MongoDB are considered more modern options. Most ...

Include a new key and its corresponding value to an already existing key within FormData

I have a form that includes fields for title, name, and description. My goal is to submit the form values using an API. To achieve this, I am utilizing jQuery to add key-value pairs to the FormData variable: formdata.append('description_text', jq ...

The method of inserting a JSON dates object to deactivate specific days

I am currently utilizing a date picker component that can be found at the following link: While attempting to use the disabledDays section below, I have encountered an issue where I am unable to apply all three options. The blockedDatesData option works o ...

Is there a way to utilize code to invoke a method of an object? For example, calling MyObject.XVariable(//some function

I have a unique object that gets its data filled from an API call. let MyDog = { Name: 'Dog', } let arrayFunctions; fetchDogsFunctions(dogAPIUrl).then(res => { // The results variable contains an array of functions the dog can do, such as get ...

Guide on converting a date input to a timestamp

I am trying to convert the date retrieved from an HTML5 date input into a timestamp and store it as a variable. HTML: <form> <section class="input"> <input type="date" id="date" name="maintenanace_date"/> </section> <sectio ...

How can we use Cypress to check if we are at the final slide in the presentation?

I am facing a challenge with multiple slideshow files that contain varying numbers of slides. Some have 10 slides, while others have 80 slides. My goal is to test every slide by using the forward and backward arrow buttons for navigation. Currently, I am c ...

Struggling to update the previousCode state with the useState hook in React

I'm having trouble understanding why the state isn't changing when using setPreviousCode in React and JavaScript. I'm trying to store the previously scanned text in the variable previousCode. import React, { useEffect, useState } from " ...