Retrieving user input from an angular controller function

I have a $resource object in Angular that looks like this:

{
  _id: '1'
  items: [
    {_id: 'a'}, {_id: 'b'}, {_id: 'c'}
  ]
}

My goal is to create a form with a checkbox for each element in the items array. In the act() function, I want to be able to identify which elements were selected using the checkboxes.

The HTML markup for the form is as follows:

<form ng-submit="act()">
  <input type="checkbox" ng-model="item._id" ng-repeat="item in items">
  <button type="submit">Submit</button>
</form>

However, I am struggling to access the array of item ids corresponding to the checked checkboxes within the act() function in the controller.

I have attempted to retrieve the values from the FormController in the scope, but I can only get the validity state from there. I have also tried binding the checkboxes to an array in the scope using ng-model, but it always remains empty in the act() function.

Answer №1

To dynamically add a field named checked to each item, you can update your controller logic to access $scope.items and filter out the checked items.

<input type="checkbox" ng-model="item.checked" ng-repeat="item in items">

$scope.act = function () {
    var checkedItems = [];
    angular.forEach($scope.items, function (item) {
        if (item.checked !== undefined && item.checked) checkedItems.push(item);
    });
    console.log(checkedItems)
}

View Demo Here

Answer №2

To keep track of the checked values, you can store them in an object with the item's id as the key. Then, filter the object to only show the values that are true (checked).

For a working example, check out this JSFiddle link.

Here is the complete controller code:

function myCtrl($scope){
    $scope.selected = {};
    $scope.var = {
      _id: '1',
      items: [
        {_id: 'a'}, {_id: 'b'}, {_id: 'c'}
      ]
    };
    
    function isChecked(obj){
        var checked = [];
        for(var key in obj){
            if(obj[key])
                checked.push(key);
        }
        return checked;
    };
    
    $scope.act = function(){
        $scope.checked = isChecked($scope.selected);
    };
}

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

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

Phonegap's JavaScript canvas feature is experiencing issues

Recently, I came across a JavaScript bouncing ball animation that works perfectly on the Chrome browser when used on a PC. However, when I tried running it using Phonegap Eclipse Android emulator, I encountered an issue where the canvas appeared blank and ...

Activating Button within Featherlight Modal

This is a follow up question from Featherlight hide div on Close After successfully resolving the issue with opening the lightbox, I have encountered another problem. I have added a submit button that should trigger an on('submit', function) whe ...

Which programming language is more suitable for developing a chat website - PHP or JSP?

My goal is to create a web-based chat application similar to Yahoo's, utilizing JSP/PHP with AJAX. I'm debating between using JSP or PHP for this project and looking for the advantages and disadvantages of each. Which do you think would be bette ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

I am unable to make changes to the Text Field component in Material-UI

After developing a React App using Material-UI, I decided to create independent Components. Below are the independent components (<PanelDiv/>): render() { return ( <div className="panelDiv-component" style={{display:this.prop ...

React Native application fails to return any values from an asynchronous operation in App function

Completely new to React Native, this is my first attempt at coding. I'm struggling with returning jsx from my App() function due to an asynchronous operation within it. Here's the code that I believe clearly demonstrates my issue: import React fr ...

Toggle the visibility of an element with a single button click

Below is a snippet of my sample code: SAMPLE HTML CODE: <ul> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <l ...

The issue of VueRouter malfunctioning in history mode within Wordpress

I have integrated Vue into my Wordpress theme, but I am facing an issue with the router when setting mode: 'history'. The site goes blank and even after trying to configure the .htaccess file, nothing seems to work. My project is located in the V ...

define a variable within a v-for loop

Example of Code <div v-for="item in dataItems"> <div v-if="enableEdit"> <input type="text" v-model="name"> </div> <div v-else> {{name}} </div> <button @click="enableEdit = true">click</button> This ...

When calling canvas.getContext('2D'), the function returns a null value

After creating a canvas and calling its getContext() method, I was confused when it returned null for the context. Below is the code snippet that I used: <script> window.onload = initializeCanvas; function initializeCanvas(){ ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

Capture sound from web browser and display live audio visualization

I'm searching for a package that can capture audio input from the browser's microphone and display it in real time. Are there any JavaScript packages available for this purpose? I've looked at various audio visualizer options, but they all r ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

Guide to setting up a TreeView with default expansion

When using a @mui TreeView, all nodes are initially collapsed by default. I am trying to figure out how to have all nodes expanded by default, but haven't been successful so far. I attempted to create a method called handleExpandAll, but it doesn&ap ...

Sending a JSON object from JSP to JavaScript using AJAX

Is there a way to transfer JSON values from JSP to JavaScript as an object using AJAX without resorting to global JavaScript variables, which can expose the JSON content in the page's source? The desired scenario is as follows: The JSP URL is opene ...

The error encountered is related to the MongooseServerSelectionError that occurs in

I have been working on setting up my first mongo-db application to connect to the server. However, I am encountering a specific error during this process: const express = require('express'); const mongoose = require('mongoose'); const ...

Discover the size of objects in three.js

Looking for a way to determine the dimensions of a mesh in three.js? I have Collada (.dae) files and need to know their size in units (x,y,z). I've heard about using geometry.computeBoundingBox(), but could use more guidance on how to implement it. ...

The issue with Webpack and Angular is that they are not properly packaging Bootstrap to

Currently troubleshooting the integration of Bootstrap into the dist version of the index page. It seems that there's an issue with bootstrap not displaying as expected. I suspect that the .angular-cli.json file is responsible for generating the webp ...