How can you make a checkbox function like a select in AngularJS?

Is it possible for AngularJS to automatically bind all values (options) when a user selects something from a list, populating them via the model? How could I achieve a similar functionality with checkboxes? I want a select for multiple values and a checkbox for single values without making significant changes to the code.

Currently, my select looks like this:

<div ng-repeat="event in allElements"
  <select ng-model="event.selectedElement" ng-change="updateSelectedElements(event);"
     <option value>Select date</option>
     <option value>{[{ getDate(event.elements) }]}</option>
  </select>
</div>

The updateSelectedElements function manipulates the list. How can I apply the same concept to checkboxes? Can a checkbox 'bind' selected elements just like a select does, even though its value is limited to true/false compared to the options available in a select?

I attempted:

<input type="checkbox" ng-model="event.selected" ng-change="updateSelectedElements(event)" />

However, event.selectedElement returns null with checkboxes, unlike with selects where it works. Do I need to manually set event.selectedElement using a function? This process confuses me.

Answer №1

If you're looking for a solution, consider implementing the following code snippet:

<input type='checkbox' ng-repeat="fruit in fruits"
  ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)">


  function SomeCtrl ($scope) {
    $scope.fruits = ["apple, orange, pear, naartjie"];
    $scope.checkedFruits = [];
    $scope.toggleCheck = function (fruit) {
        if ($scope.checkedFruits.indexOf(fruit) === -1) {
            $scope.checkedFruits.push(fruit);
        } else {
            $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1);
        }
    };
}

Here are some references that may be helpful: Link 1 Link 2

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

Is it permissible to use Aloha editor GPL v.2 on a business website?

While researching the licensing of Aloha Editor, I came across some confusing information. I found a reference to another editor under LGPL: However, I couldn't find a clear answer on whether I can use Aloha JS code on a commercial website with GPL v ...

Error message "Slice of undefined" occurs while attempting to use pagination within an ng-repeat loop

My goal is to implement pagination on the ng-repeat results in my list. I want to display only 2 results initially and then have next and previous buttons that function accordingly. This is the code for my controller: <script> var app = angular ...

Decreased Performance in Vue Threejs with Larger JSON Data Sets

I am currently upgrading a legacy Three.js project from Angular 1.5 to Vue 2.6. The project is used for visualizing objects in JSON file format and I'm experiencing a drop in frame rate, going from ~60FPS in Angular to ~12FPS in Vue when loading large ...

Deactivate web security for JavaScript with Watir

While using Watir, I have the ability to access the methods of the iframes on the page: browser.iframes.map(&:contentwindow) # => ["", "", ""] However, if I try to access the iframes using JavaScript within the same context where I executed the W ...

Turning a JSON dot string into an object reference in JavaScript: A simple guide

Having a JSON object labeled test with values like this: {"items":[{"name":"test"}]}, I need a way to apply the string items[0].name to it in order to search for a specific value (test.items[0].name). Currently, my only idea is to create a function that pa ...

p5.js experiencing issue: Uncaught TypeError - Unable to access property 'transpose3x3' due to null value

I have a simple website built with Flask where I am running several p5.js sketch animations, and everything is working smoothly. However, when I try to add a new sketch that utilizes WEBGL, I encounter the following error: Uncaught TypeError: Cannot read p ...

Ideal location to detect web browser and display or conceal a division

I am looking to display a div using either the ng-if or ng-show/hide directives if the user accesses the page through a specific browser, such as Chrome/Chromium. However, I am unsure of the optimal location to place this functionality. The JavaScript cod ...

How to Toggle Div Visibility with AngularJS ng-show and ng-click

In order to eliminate error messages, I decided to clear the field with a button click. This approach successfully removed the error in my initial test. <div class="errorPopup" data-ng-click="runner.Name = null" data-ng-show="mainForm.name.$error.pat ...

Is it possible to capture every ajax request?

My goal is to intercept all AJAX calls and check for specific error codes (ACCESS_DENIED, SYSTEM_ERROR, NOT_FOUND) in the response JSON sent from my PHP script. One approach I've seen is: $('.log').ajaxSuccess(function(e, xhr, settings) { ...

Ways to retrieve information when text is modified and a dropdown is selected within an input field

I have an input field with a text box and a dropdown. My goal is to trigger data based on text changes in one method, while using another method for the dropdown. Check out the code below. const allList = [ { id: "1", value: "Fruits" ...

Managing multiple dropdown menus in PHP when dealing with Select options

In the given script, I am attempting to manage the selection between a dropdown option and the value of a text field: <script> function check() { var dropdown = document.getElementById("OpType"); var current_value = dropdown.options[dropdown ...

Are there any options for a JavaScript coding platform that can be used on a tablet device?

As someone who frequently travels by train, I recently purchased an Android tablet and have a strong desire to learn JavaScript. While I can read books on my tablet, I am eager to also be able to program on it. Are there any options available for develop ...

Is it possible to assign an interface to an object property in TypeScript?

I am currently working with an object that looks like this: export class Section{ singleLabel:string; pluralLabel:string; index:number; dataInterface:Interface; } My goal is to assign an interface to the dataInterface field, as I need to use the S ...

What is the best method for determining the height of a sandboxed iframe?

My website includes an iframe with the sandbox attribute. Users can set the content of this iframe directly through the 'srcdoc' attribute, which raises security concerns. I am trying to find a way to dynamically adjust the height of the iframe ...

Exploring an array to retrieve a specific value

Can someone assist me? I am looking to create a JavaScript function that follows the structure of the code example below. Unfortunately, I do not have enough programming skills to develop a functional solution from scratch. The goal is to input a value, ...

Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them. Below is my current rollup configuration: import path from 'path'; import pat ...

Global error handling for URQL GraphQL mutation is a critical aspect that needs to be effectively implemented

Here's the technology stack I'm using: react v17.0.2 graphql v16.8.0 graphql-ws v5.14.0 urql v4.0.5 I rely on Hasura Actions to interact with a REST API and am in need of a solution for handling global errors for all mutations. For instance, I ...

Is it possible to utilize the same database connection for multiple routes in an

I have taken inspiration from Express's route-separation example and created a Node.js app. Now, I aim to enhance it by integrating the MongoDB driver Mongoose for listing Users and Kittens. var express = require('express'); var app = expre ...

Creating a guideline for input to allow for both empty strings and a set number of characters

How can I set a rule for input to only allow two conditions: The input must be exactly 5 characters long. The input can also accept an empty string. Here is what I've done so far: new Vue({ el: '#app', data: () => ({ code: ...

"Exploring the method of aggregating markers into a single point when zoomed out using Google Maps API

My web app features a Google Maps view. I have designed custom markers with unique info views for each one. As users zoom out, I want to avoid cluttering the map with numerous individual markers. Instead, I would like to group them together with a number ...