Learn how to properly register the order of checkboxes in AngularJS

I have a unique requirement for my webapp where I need to display the order in which checkboxes are checked. I came up with the following code to achieve this functionality:

$scope.updateNumbers = function(id, checked, inputs) {
    if (checked === true) {
        $scope.count += 1;
        var span = angular.element('#'+id+'-'+id);
        span.html($scope.count);
    } else {
        if ($scope.count != 0) {
            $scope.count -= 1;
        }

        for (index = 0; index < inputs.length; ++index) {
            var input = inputs[index];

            var span = angular.element('#'+test.id+'-'+test.id);
            if (span.html() > $scope.count || span.html() == $scope.count) {
                span.html(span.html()-1);
            }
        }

        var span = angular.element('#'+id+'-'+id);
        span.html($scope.count);
    }
}

Here's the corresponding HTML:

<div class="list-view__body__row" ng-repeat="restaurant in restaurants">
    <div class="list-view__body__cell">
        <input type="checkbox" id="<% restaurant.id %>" value="" 
          class="input-field__checkbox--input" 
          ng-model="restaurant.checked" 
          ng-change="updateNumbers(restaurant.id, restaurant.checked, restaurants)">
        <label for="<% restaurant.id %>" 
          class="input-field__checkbox--label" 
          ng-bind-html="restaurant.name|html"></label>
    </div>
    <div class="list-view__body__cell">
        <div class="order__wrapper" ng-show="restaurant.checked">
            <span id="<% restaurant.id %>-<% restaurant.id %>">0</span>
        </div>
    </div>
</div>

Unfortunately, the current implementation is not working as expected - sometimes the number goes down to 0 or numbers appear twice. How can I enhance this code to work correctly?

Answer №1

When working with Angular, it's important to let your data model dictate how the view is displayed. This approach eliminates the need for manual DOM manipulation as Angular handles the DOM based on the provided data. And best of all, it requires minimal code.

All you need is an array in your data model to keep track of the checked restaurants. The order of the restaurants is determined by the index within this array, and the count is simply the length of the array.

Controller:

  // array to store selections
  $scope.checkedItems=[];

  $scope.updateSelections = function(rest){        
    if(rest.checked){
      // add to array if item is checked
      $scope.checkedItems.push(rest)
    }else{
      // remove from array if not checked
      $scope.checkedItems.splice($scope.checkedItems.indexOf(rest),1)
    }
  }

View:

<div ng-repeat="restaurant in restaurants">
    <div>
      <input type="checkbox" ng-model="restaurant.checked" 
             ng-change="updateSelections(restaurant)">
      <label ng-bind="restaurant.name"></label>
    </div>        
    <div ng-show="restaurant.checked">
        <!--   Use index to display order -->
        Order: <span>{{checkedItems.indexOf(restaurant) +1}}</span>
    </div>        
  </div>

  <h3>Count of checked items: {{checkedItems.length}}</h3>

DEMO

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

How to Send an Array to AJAX and Retrieve the Data in Codeigniter Controller

I am attempting to retrieve table data, store it in an array, and pass it to the controller so I can write it in PHP Excel. Previously, I had success with other data but now my excel file is turning up empty. Below is the JavaScript code snippet: var Ta ...

Dynamically updating the ng-class name in AngularJS

Exploring the integration of animate.css with AngularJS. Attempting to assign a class to an element on ng-click, but facing difficulties in updating the element. Various strategies were attempted, including modifying scope values through functions, without ...

Is it feasible to relocate an embedded swf file from one tag to another?

My HTML contains two containers for embedded swf files: <div id="player1"></div> <div id="player2"></div> If I load an embedded video into the first div (player1) like this: swfobject.embedSWF("someURL","player1"); Is it possibl ...

React: Implementing localStorage token addition in loginHandler function using State hook is not functioning as expected

I've implemented an AuthContextProvider in my React application to handle user authentication and logout functionality: import React, { useState } from "react"; import axios from "axios"; import { api } from "../api"; co ...

Tips for utilizing jQuery Ajax data action

I've been trying to understand how to effectively utilize the data parameter in a $.Ajax call. However, I am facing confusion regarding the 'action' part within the data call. Is it meant to trigger an action in a controller? If so, how can ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...

Issue with a Bootstrap panel displaying incorrect border formatting

I am currently working with Angular UI Bootstrap and facing an issue with an accordion component. Everything works perfectly fine in the development environment with the full version of the Bootstrap Cerulean file. However, when I minify the CSS file for p ...

Creating a time-limited personal link with Django Rest Framework and React

I have a frontend application built with React Framework that I want to provide access to via a time-limited personal link, without the need for additional authentication functions. With approximately 1-2 new users per day, my proposed implementation is as ...

Upon introducing the CSS loader into the webpack configuration, TinyMCE unexpectedly ceases to function

My application development journey began with cloning code from https://github.com/DMPRoadmap/roadmap. This project is based on webpack and npm. To integrate select2, I executed npm install select 2 in the lib/assets directory. I aimed to incorporate a ...

Pagination Component for React Material-UI Table

I am interested in learning about Table Pagination in React UI Material. Currently, my goal is to retrieve and display data from an API in a Material UI Table. While I have successfully implemented some data from the API into the Material UI Table, I am ...

Is the AngularJS version significant in determining outcomes?

Just delved into the world of AngularJS and encountered a puzzling issue. Here's what I've been struggling with: I crafted a piece of code in app.js var myApp = angular.module("myApp",[]); myApp.config(['$routeProvider', function($ro ...

What's the best way to constrain a draggable element within the boundaries of its parent using right and bottom values?

I am currently working on creating a draggable map. I have successfully limited the draggable child for the left and top sides, but I am struggling to do the same for the right and bottom sides. How can I restrict the movement of a draggable child based o ...

The RefreshIndicator from Material-UI fails to display during the first page load

I am facing an issue with displaying a loading icon during the initial page load. The code appears to be correct to me but for some reason, the loading icon is not showing up. I am utilizing the RefreshIndicator component from material-ui for the loading i ...

The issue of unselection not functioning properly for multiple items when using both selectable and draggable features

i need the unselection of list items to be as smooth as selectable() but without draggable() My desired outcome is similar to the following gif showcasing combined selectable and draggable functionality: https://i.stack.imgur.com/3GjTD.gif here's t ...

Utilize associative arrays to efficiently filter ng-repeat

Having an associative array (or object to be more precise) $scope.items = { 'x': {...}, 'y': {...} }; Wanting to use ng-repeat which is functioning properly <div ng-repeat="(id, data) in items | filter: customFunction" > But t ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

Obtaining the accurate offsetTop and offsetLeft values for an element following a CSS3 rotation

Is there a method to accurately determine the offsetTop and offsetLeft values of an element post-transform rotation? Are there any lesser-known element properties that could be helpful in this scenario? Attached is an image that can provide further clari ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...