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

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

What is the best way to obtain the final visible element using jQuery?

Could you please check out the following link: http://jsfiddle.net/SHfz4/ All of the blue boxes are technically visible, so I can't use the code $('.row .inner .item:visible:last'); as it will always return box 27. Some boxes may not be v ...

Why is my Node.js Connect middleware Limit feature not functioning as expected?

Having an issue with server: var connect = require('connect'); var http = require('http'); var app = connect() .use(connect.limit('32kb')) .use(connect.urlencoded()) .use(connect.json()) .use(function(req, res){ console. ...

Targeting props within a Class Component: A Step-by-Step Guide

I am currently working on a MultiStep Form project. On the final page of the form, my goal is to push all the collected data to Firebase. I have been utilizing props and states to pass values from one page to another. However, I'm facing an issue in t ...

Ways to conceal components upon clicking a different element

Struggling to make this jQuery function properly. I have a form with all fields contained in a div.form-group. The subscribe button is identified by the id subscribe. I'm aiming to hide the form fields when clicked, but my JavaScript doesn't see ...

Hide the previous dropdown content in Vue JS by manipulating the visibility of the elements

I'm currently working on creating a Dropdown feature, but I'm facing an issue with hiding the dropdown content when another dropdown is clicked. <template> <div class="dropdown-container"> <div v-for="(it ...

Getting the ng-view feature in AngularJS to function properly

Searching for a solution to create a single page application using angularjs. Successfully set up routes and partial pages are loading in ng-view properly. The struggle is with loading external json data - it was working before but now I can't seem to ...

"Interacting with the ng-keypress event causes the page to smoothly scroll

As a newcomer to angularjs, I am trying to figure out why my component (which simulates a "checkbox" using fontawesome icons) causes the page to scroll down when the user presses the space key. Here is a snippet of my component : ugoFmk.component(' ...

Ways to incorporate services into functions within Angularjs

I'm struggling to grasp the concept of dependency injection in AngularJS. Currently, I am attempting to inject $interpolate and $eval into my controller. However, after consulting the documentation, I realized that my lack of foundational knowledge i ...

Acquire the S3 URL link for the uploaded file upon completion of the file upload process

Is there a way to securely upload and generate a public Amazon S3 URL for a PDF file when a user clicks on a specific link? I'd like to avoid exposing the actual link to the user by uploading it to S3. Here's a sample code snippet: module.expo ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

Error encountered when downgrading a component from Angular v5 or v4 to AngularJS due to an injector issue

I have successfully created a basic angular5 component called HelloComponent: var HelloComponent = function () { }; HelloComponent.annotations = [ new ng.core.Component({ selector: 'hello-world', template: 'Hello World!' } ...

New data row successfully added to HTML table, revealing an object display

When I click a button, a dialog box opens up. I can fill out the form inside the dialog box and submit it to insert a row into a table. After submitting the form, the newly inserted row displays as [object Object] immediately after submission: It seems t ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Unable to download the jQuery Plugin

I am looking to install a gallery without using flash, and I came across this jQuery plugin called Grid-A-Licious. However, I am having trouble figuring out how to install and use it since it is distributed as a .zip archive with two .js files but no index ...

Is there a way to minimize the number of Nuxt pages on a website?

Consider creating a large nuxt application with 100 routes. What strategies would you recommend for effectively managing these routes within the app, excluding micro-frontend solutions? ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Tips for building a versatile fetch function that can be reused for various JSON formats within a React application

Using the fetch method in various components: fetch(url) .then(result => { if (!result.ok) { throw new Error("HTTP error " + result.status) } return result.json() }) .then(result => { ...

Tips for sending a successful POST request with the MEAN stack

Currently, I am utilizing yeoman to set up a new project. My ultimate goal is to master the process of scaffolding CRUD operations. However, I have encountered an issue with a post request. For this reason, I opted for the angular-fullstack generator as I ...