Implement a checkbox selection feature using ng-model in AngularJS for multiple items

Setting up the controller below allows me to add checked values into an array.

(function (app) {
  'use strict';
  
  app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
    // fruits
    $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
    
    // selected fruits
    $scope.selection = ['apple', 'pear'];
    
    // toggle selection for a given fruit by name
    $scope.toggleSelection = function toggleSelection(fruitName) {
      var idx = $scope.selection.indexOf(fruitName);
      
      // is currently selected
      if (idx > -1) {
        $scope.selection.splice(idx, 1);
      }
      
      // is newly selected
      else {
        $scope.selection.push(fruitName);
      }
    };
  }]);
})(angular.module('app', []));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="SimpleArrayCtrl">
        <div class="row">
          <div class="col-md-6">
            <h4>selectables</h4>
            <form class="form-group" novalidate name="test">
              <label ng-repeat="fruitName in fruits" class="checkbox-inline">
                <input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)"> {{fruitName}}
              </label>
            </form>
          </div>
        </div>

        <div class="row">
          <div class="col-md-6">
            <h4>selection</h4>
            <pre>{{selection|json}}</pre>
          </div>

          <div class="col-md-6">
            <h4>inputs</h4>
            <pre>{{fruits|json}}</pre>
          </div>
          <div class="col-md-6">
            <h4>form</h4>
            <pre>{{test|json}}</pre>
          </div>          
        </div>
      </div>
  </div>

I am aiming to bind the array value into the form in order to submit the contents of the array.

Adding ng-model to my checkbox input only gives me true or false in the array instead of the actual value.

                <input ng-model="fruitName" type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)">

Is there a way to bind the value of selection to the model while keeping the checkbox ticked so that I can submit the array value when submitting the form?

Answer №1

ngTrueValue (ng-true-value="") Define the specific value that the expression will take when the checkbox is selected.

ngFalseValue (ng-false-value="") Specify the value that the expression will have when the checkbox is not selected.

To see an example, check out this link: https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D

Answer №2

If you're looking for a solution, you might want to consider utilizing this specific directive. It worked like a charm in my case - check out the source code

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

Incorporating sass into your Antd and Create React App workflow

Trying to combine SASS with antd and CRA has been a bit of a challenge for me. Despite following various tutorials, most of them seem outdated and result in errors. Fortunately, I stumbled upon an article that actually works smoothly link However, I can& ...

Tips for preventing multiple counter buttons from conflicting with one another

Currently, I am in the process of creating an online restaurant platform that allows customers to place food orders. To streamline this process, I am developing individual cards for each food item available on the menu. In addition, I am implementing butto ...

Overlaying content: Innovative dropdown menu design

My goal is to create a dropdown box that overlays the content of a div when an icon within it is clicked. However, currently, the dropdown box is pushing down the content of the div instead of overlaying it. I have tried adjusting my CSS by setting some el ...

Tips for creating a responsive input field within a navbar

Can anyone assist me with setting the input field width in my navbar to adjust to the remaining width of the navbar and be responsive to different device sizes? I need the input field to dynamically change its width based on the screen size. Any help would ...

Prevent my application from being idle (Cordova/Android)

I have recently developed an Android app using a node.js webpack project. After installing the app on my phone, I observed that it enters a sleep mode along with the phone. Consequently, a JavaScript timer I set up stops functioning as intended: pingTime ...

Obtain the value of a jQuery variable in TypeScript

I'm attempting to utilize the jQuery $ajax() function to call a Web API. After making the call, I am trying to figure out how to store the result in my TypeScript variable. $.ajax({ method: "POST", url: 'URL', data: { email:'exa ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

What could be the reason for the CORS failure when making requests from an HTTPS domain to an HTTP localhost

I have a secure rest service (implemented as an Azure Function), hosted on HTTPS, under domain A. My website is also running securely on HTTPS but on domain B. I've set the CORS to use a wildcard *. Using jQuery on my website, I send Ajax requests ...

How can I show the real width of an image on a mobile device?

I have integrated the infinite slide plugin from jQueryscript.net into my website. While it works perfectly on desktop with background images, I am facing an issue on mobile devices where the image width needs to be displayed in full. I attempted to adjust ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...

Closing notifications in Bootstrap 5.1 with the help of Ajax

I am utilizing bootstrap 5.1 alerts to display custom messages after an Ajax call. I also want the ability to dismiss the alert as necessary, which can be done with a dismiss button provided by bootstrap. Below is the PHP code I am using : <div class=& ...

JQuery HTML form validation continues to send emails even when there are blank entries

I've set up an HTML form with three required fields, and I'm trying to prevent the form from submitting an AJAX call if those fields are left empty. $("#contact").submit(function(e){ e.preventDefault(); var ajaxurl = '<?php echo ...

Preventing scrolling in jQuery UI Draggable when using flexbox

In my project, I am looking to organize a container using jQuery UI draggable/droppable feature. Since the elements in my list are arranged in a straight horizontal line, I have utilized display: flex. This arrangement works well when adding new items to ...

Is it possible to execute angular's method within the chrome console?

I was curious about whether I can execute an Angular method in the Chrome console. Since the method in Angular is not a global object, I am unsure how to access it. eg: var app = angular.module('myApp',[]); app.controller('MainController&a ...

Previewing multiple images before uploading them using jQuery

Currently, I am utilizing the following code for my image uploader: HTML: <input type="file" id="files" name="files[]" multiple /> <ul id="list"></ul> JavaScript: function handleFileSelect(evt) { var files = evt.target.files; // FileL ...

Issue with uppercase letters within a text input field

Imagine having an <input> and a <textarea> along with some JavaScript code that sends the value of the <input> to the <textarea> with additional text. How can you achieve this task? The text-transform: capitalize property is set in ...

Update the displayed number on the input field as a German-formatted value whenever there is a change in the input, all while maintaining

In German decimal numbers, a decimal comma is used. When formatting, periods are also used for grouping digits. For example, the number 10000.45 would be formatted as 10.000,45. I am looking to create an input field (numeric or text) where users can input ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...

I am looking to implement a straightforward drag-and-drop feature using jQuery

Is it possible to drag and select 4 buttons in a browser, similar to how you would do on Windows, using jQuery locally? ...

Convert a JSON array into a JavaScript array?

Similar Question: How can I extract property values from a JavaScript object into an array? I am receiving a JSON array from a basic server and need to parse it into JavaScript for use in my web application. What is the best way to convert a JSONP ar ...