Connect the checkbox identities to an array

Within my view model exists an object that serves to showcase a series of checkboxes:

components =  {
  "ComponentInfos": [
    {
      "Id": "1abb0ee5-7e44-4e45-92da-150079066e99",
      "FriendlyName": "Component1",
      "LimitInfos": [
        {
          "Id": "4b7cd37a-2378-4f4f-921b-e0375d60d19c",
          "FriendlyName": "Component1 Full",
        },
        {
          "Id": "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2",
          "FriendlyName": "Component1 Light",
        }
      ]
    }

The creation of checkboxes with FriendlyName as the label is successful:

<h4>{{l.FriendlyName}}</h4>

<div>
    <div ng-repeat="limitinfo in l.LimitInfos">
        <label>
            <input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]" 
            value="{{limitinfo.Id}}"/> {{limitinfo.FriendlyName}}
        </label>
    </div>
</div>

The main goal is to store the selected LimitInfo.Id in an array for each checkbox that is checked. The storage has been accomplished within an object structured as follows:

settings = {
    "ComponentInfos" : {}
  }; 

For clarity, here is an example output:

"2e80bedb-4a18-4cc4-bdfd-837ffa130947": true,
"add1edf8-4f11-4178-9c78-d591a6f590e3": true

The ultimate target is to save the LimitInfo.Id values into an array like this:

settings = {
    "ComponentInfos" : []
  };

Desired outcome:

"2e80bedb-4a18-4cc4-bdfd-837ffa130947", "add1edf8-4f11-4178-9c78-d591a6f590e3"

To view the code, it can be found onPlunker.

Answer №1

To add an item to an array when a checkbox is clicked, you can utilize the ng-click method along with a custom controller function.

<input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]" 
                value="{{limitinfo.Id}}" ng-click="toggleSelection(limitinfo.ImpliedLimits)"/> 

$scope.toggleSelection = function toggleSelection(item) {
    var idx = $scope.vm.settings.ComponentInfos.indexOf(item);
    if (idx > -1) {
      $scope.vm.settings.ComponentInfos.splice(idx, 1);
    }
    else {
      $scope.vm.settings.ComponentInfos.push(item[0]);
    }
};

Check out this example on Plunker.

For more information, refer to this helpful answer

Answer №2

Quick and easy solution

If you're looking for a simple solution using vanilla JavaScript (ES5 and later), here is an example that can be used in modern browsers:

var data = {
    "a": true,
    "b": false,
    "c": true,
    "d": false,
    "e": true,
    "f": true
}

var arr = Object.keys(data).filter( key => !!data[key] );

// This will return ['a', 'c', 'e', 'f']

Answer №3

Check out the Demo created by directive:

var app = angular.module('plunker', []);

app.directive('myCheckbox',function(){
  return {
    restrict:'EA',
    template:'<label>'
                +'<input type="checkbox" ng-model="model" ng-change="toggleModel()" /> {{label}}'
            +'</label>',
    replace: true,
    scope:{
      label:'@',
      value:'@',
      output:'='
    },
    link:function(scope,elements,attrs){

      //init checked status
      scope.model=scope.output.indexOf(scope.value) > -1;
      
      //binding click replace watch model
      scope.toggleModel = function(){
        if(scope.model){
          scope.output.push(scope.value);
          return false;
        }
        scope.output.splice(scope.output.indexOf(scope.value),1);
      }
      
    }
  }
  
});

function MyViewModel()
{
  this.components =  {
  "ComponentInfos": [
    {
      "Id": "1abb0ee5-7e44-4e45-92da-150079066e99",
      "FriendlyName": "Component1",
      "LimitInfos": [
        {
          "Id": "4b7cd37a-2378-4f4f-921b-e0375d60d19c",
          "FriendlyName": "Component1 Full",
          "ImpliedLimits": [
            "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2"
          ]
        },
        {
          "Id": "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2",
          "FriendlyName": "Component1 Light",
          "ImpliedLimits": [
            "4f74abce-5da5-4740-bf89-dc47dafe6c5f"
          ]
        },
        {
          "Id": "4f74abce-5da5-4740-bf89-dc47dafe6c5f",
          "FriendlyName": "Component2 User",
          "ImpliedLimits": []
        }
      ]
    },
    {
      "Id": "ad95e191-26ee-447a-866a-920695bb3ab6",
      "FriendlyName": "Component2",
      "LimitInfos": [
        {
          "Id": "8d13765a-978e-4d12-a1aa-24a1dda2149b",
          "FriendlyName": "Component2 Full",
          "ImpliedLimits": [
            "4f74abce-5da5-4740-bf89-dc47dafe6c5f"
          ]
        },
        {
          "Id": "2e80bedb-4a18-4cc4-bdfd-837ffa130947",
          "FriendlyName": "Component2 Light",
          "ImpliedLimits": [
            "4f74abce-5da5-4740-bf89-dc47dafe6c5f"
          ]
        },
        {
          "Id": "add1edf8-4f11-4178-9c78-d591a6f590e3",
          "FriendlyName": "Component2 Viewer",
          "ImpliedLimits": [
            "4f74abce-5da5-4740-bf89-dc47dafe6c5f"
          ]
        }
      ]
    }
  ]
};

  this.settings = {
    "ComponentInfos" : ["4b7cd37a-2378-4f4f-921b-e0375d60d19c","2e80bedb-4a18-4cc4-bdfd-837ffa130947"]
  };
}



app.controller('MainCtrl', function($scope) {
  $scope.vm = new MyViewModel();
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2b242d3f262b386420390a7b64796432">[email protected]</a>" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div ng-repeat="l in vm.components.ComponentInfos">

    <h4>{{l.FriendlyName}}</h4>

    <div>
        <div ng-repeat="limitinfo in l.LimitInfos">
            <my-checkbox label="{{limitinfo.FriendlyName}}" value="{{limitinfo.Id}}" output="vm.settings.ComponentInfos"></my-checkbox>
        </div>
    </div>
  </div>
  
  
  <hr>
  <pre>
    {{vm.settings | json }}
  </pre>
  
  </body>

</html>

Answer №4

To update your list, utilize the ng-click function within your MyViewModel. Modify the type of ComponentInfos to an array as shown below.

this.update = function (value) {
    var exists = false;
    for (var elem of this.settings["ComponentInfos"]){
      if (elem === value) {
        exists = true;
      }
    }

    if(exists) {
      var index = this.settings["ComponentInfos"].indexOf(value);
      this.settings["ComponentInfos"].splice(index,1);
    } else {
      this.settings["ComponentInfos"].push(value);
    }
  }

Furthermore, adjust the input in the HTML like so:

<input type="checkbox" ng-click="vm.update(limitinfo.Id)"/> {{limitinfo.FriendlyName}}

Answer №5

Just starting out with angularJS? Here's a helpful tip:

Copy and paste the following code into your app.js file:

this.data =[];
this.selection = function(){
    this.data =[];
    angular.forEach(this.settings["ComponentInfos"], function(value, key) {
      if(value)
        this.push(key);
    }, this.data);
 }

Insert this code snippet into the body of your index.html file:

<div ng-repeat="l in vm.components.ComponentInfos">

<h4>{{l.FriendlyName}}</h4>

<div>
    <div ng-repeat="limitinfo in l.LimitInfos">
        <label>
            <input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]" ng-click="vm.selection()"
            value="{{limitinfo.Id}}"/> {{limitinfo.FriendlyName}}
        </label>
    </div>
</div>
</div>
<hr>
<pre>
 {{vm.settings | json }}
 {{vm.data}}
</pre>

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 input field does not retain decimal numbers and automatically changes them to ,00

Working on a website and I encountered an issue with an input field that needs custom decimal numbers. When I enter 36.82 and click save, it changes to 36.00. Code : <tr> <td>Btw tarief: </td> <td><input type="text" n ...

Generate a unique ID each time the page is loaded or refreshed

I'm currently working on a function that will display a unique ID or a different video each time the page is loaded or refreshed. My main objective is to design a splash intro popup that features a <section> with a full-screen YouTube video bac ...

Tips for achieving asynchronous behavior using nested iterations in Firebase's forEach function

I have a collection of items, with each item linked to multiple transaction records. - items - itemA - transactionA - transactionB - itemB - transactionC - transactionD In my express application, I need to create an endpoint ...

Having trouble with Angular Material's Check All and Uncheck All functionality?

I have successfully created a Multi-select dropdown with 'Select all' and 'Deselect all' options. However, I am facing an issue where the checkboxes for select all and deselect all work only once and then stop functioning. Can anyone as ...

What is the method for invoking a Java class object within a JavaScript function without using ajax?

When it comes to programming, Java is commonly used for server-side operations while JavaScript is typically utilized for client-side actions. For example, in AJAX, we initialize an XMLHttpRequest object by declaring xhr = new XMLHttpRequest(); in JavaScr ...

Guide to creating a nested table with JavaScript

Currently, I am utilizing JavaScript to dynamically generate a table. To better explain my inquiry, here is an example of the HTML: <table id='mainTable'> <tr> <td> Row 1 Cell 1 </td> ...

Combining Ng-model with iOS credit card scanning functionality offers a seamless and

Dealing with Ng-model and iOS credit card scanning In my credit card form, each field is structured like this: <input type=“text” ng-model = “cc.number”, ng-class = validClass('cc.number’)> The function validClass returns either val ...

What is the best way to display or conceal buttons when the textarea is in focus or out of focus, while still allowing them

Seeking help to include two buttons beneath the input box. One button is for saving the input in the textarea, while the other is for aborting. The buttons should only be visible when the input field is focused. An issue I am facing is that clicking on ...

Go back to the pop-up window if an error occurs

I've implemented a modal window in front of my index page. When the model is valid, I redirect to the index view. However, when the model is not valid, I want it to stay on the modal. How can I achieve this? [HttpPost] [ValidateAntiForgeryToken] publ ...

Blending the power of google-maps-react with the versatility of react-router

While working on my project, I encountered an issue with google-maps-react. It seems that when I try to include a <Link /> from react-router-dom alongside multiple <Marker />, there is a conflict. This is the structure of my code: render() { ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

Exploring the capability of utilizing undefined properties within the ng model in Angular

Received a code and noticed that the properties like user.name or user.email are being used in ng-model without being declared in the controller. How is it still functioning? How can we send user information to the controller function using ng-click="upda ...

The non-null value retrieval function is malfunctioning while attempting to save data into MongoDB

After retrieving an array of objects from an API call, I apply filtering based on two keys: story_title and title. If both values are null, the object gets filtered out. Subsequently, I iterate through the filtered array to store specific data in mongodb u ...

Elements overlapped with varying opacities and responsive to mouse hovering

In this Q/A session, we will explore a JS solution for managing the opacity of overlapping elements consistently during hover. Objective Our goal is to create two transparent and overlapping elements, similar to the red boxes showcased below. These eleme ...

Form values not being transmitted correctly in Ajax POST request

I'm facing an issue with my form submission through AJAX where the values are coming out incorrect. Strangely, when I use a normal POST submit it works perfectly fine! <script type="text/javascript"> $(function () { $('#B ...

Hide the submit button once more following a click action, triggered by form validation with ng-show

I am trying to achieve a specific functionality with my code. Currently, the code displays the 'a.btn' anchor if both inputs have values and the 'inputURL' is a valid URL. Everything works as expected, however, I now want to hide the bu ...

What is the best way to increase scrollTop in relation to the desired scroll distance of a different element?

fiddle: http://jsfiddle.net/DerNalia/88N4d/9/ My Objective: I want the Sidebar(s) to remain fixed on the page when there is enough space for them. If there isn't enough room, the Sidebar(s) should scroll along with the content. Once the bottom ...

Tips for organizing bower dependencies efficiently

I'm currently working on an HTML-based project and utilizing a bower.json file to manage all the dependencies: { "name": "MyProject", "version": "0.1", "main": "index.html", "dependencies": { "modernizr": "2.8.3", "classie": "1.0.1", ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Utilizing Ajax and jQuery to verify the initial password input in real-time as the user types

My goal is to create a Change Password page where users can enter their original password and have it instantly checked for correctness without the need for page refresh. I want to display a checkbox image next to the text box when the password is correct. ...