Creating a dynamic checkbox feature in Angular using iterations

I'm currently working on a loop that generates checkboxes from a collection. Everything works fine so far, but now I need to set a limit of 8 checkboxes that can be checked (while still displaying all checkboxes).

I attempted to use ng-model (and also tried ng-if) within the class as shown below, but the behavior is not what I expected.

HTML

<div class="col-xs-12 col-sm-4 " ng-hide="vm.resultCount === 0" ng-repeat="np in vm.corporations">
  <div class="Checkbox">
    <input type="checkbox" ng-click="vm.updateCart(np)"/>
      <div class="Checkbox-visible" model="!vm.overEightCorporations">

CSS

> input:checked + .Checkbox-visible {
    background: #000 url('../images/CheckMark_White.png') center/20px 20px no-repeat;
}

> input:focus + .Checkbox-visible {
}

JS

vm.overEightCorporations = function () {

        if ($rootScope.cart.length > 7){
            return true;
            toastr.error('You can only set 8 corporations at a time.');
        }
        return false;
        }
    };

edit:

Additional JS after responses

       vm.updateCart = function (corporation) {

            var i = vm.inCart(corporation.id);
            if (i < 0) {
                $rootScope.cart.push(corporation);
            } else {
                $rootScope.cart.splice(i, 1);
            }

    };

Answer №1

If you want to control the number of items displayed in your ng-repeat, you can use the limitTo filter.

<div class="col-xs-12 col-sm-4 " ng-hide="vm.resultCount === 0" ng-repeat="np in vm.corporations | limitTo: 8">
  ...
</div>

Answer №2

When it comes to updating the cart, you'll want to follow a similar approach as outlined below:

  vm.updateCart = function (corporation) {
        var i = vm.inCart(corporation.id);
        if (i < 0) {
            $rootScope.cart.push(corporation);
        } else {
            $rootScope.cart.splice(i, 1);
        }

        // If you need to display an error message, this is where you can do so
        vm.overEightCorporations = $rootScope.cart.length > 7;

};

For the HTML code:

<div class="col-xs-12 col-sm-4 " ng-hide="vm.resultCount === 0" ng-repeat="np in vm.corporations">
  <div class="Checkbox">
    <input type="checkbox" ng-click="vm.updateCart(np)" ng-class="{ 'checkbox-invisible': vm.overEightCorporations }"/>
      <div class="Checkbox-visible">

And for the CSS styling:

input[type="checkbox"]:not(:checked) + .checkbox-invisible {
     display:none;
}

Answer №3

After adding a "checked" boolean to my data object, I was able to resolve the issue. It required me to include the object at instantiation and make modifications in various parts of the code to ensure it stayed current. The problems persisted until I switched from using ng-click to ng-change, which seems to work more effectively with ng-model. Finally, I was able to indicate the presence of a check mark simply by using the checked boolean:

 <input type="checkbox" ng-change="vm.updateCart(np)" ng-model="np.checked"/>

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

Newcomers to Visual Studio Code facing a problem with images not displaying

As a beginner in all aspects, I am currently facing an issue with displaying an image on Visual Studio Code. The problem arose when I tried to create a separate folder for the image, which resulted in a cascade of subfolders that only made things worse eac ...

Ways to duplicate a letter in HTML?

How can a character be printed repeatedly within a table cell using only HTML or HTML and CSS (excluding HTML5)? *(limiting to only HTML or a combination of HTML and CSS) ** The goal is to print the character "." across the entire length of the cell, wit ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

How to connect a checkbox and a listbox in Angular 2

I am trying to create a functionality in Angular 2 where I have a checkbox with three options. Each option should be bound to a different select list, so that when the checkbox is checked, the corresponding list box is displayed. Can anyone guide me on h ...

showing information on webpage 2 received via query parameters from webpage 1

Hello, I am trying to input text into a textarea and then send the data through a query string to another webpage. My goal is to display the data on the second webpage. I have written the following code, but it doesn't seem to be working. I've ch ...

Using jQuery.dataTables to choose all rows except the final column

I'm utilizing a table with jQuery.dataTables. I have a requirement to input dates in the last column. However, when I click to input a date, the row becomes deselected. The following code is meant for selecting all rows: Displayed below is the DataT ...

Mobile Device Centering Problem with Bootstrap Cards

Despite my thorough research efforts, I have been unable to find a solution. The code snippet below is meant to display the image provided, but it seems to shift to the left when viewed on a mobile device. If anyone can assist me with this issue, I would ...

Ionic 2 hides the form input area within its input component

I set up a login page, but the input fields are not showing up on the form. Here is my current code: <ion-list> <ion-item> <ion-label fixed>Username</ion-label> <ion-i ...

Creating button text wrapping with Bootstrap 5

My goal is to design a button using Bootstrap 5 that has a unique appearance. I came across a similar post on Stack Overflow but couldn't find a solution that fits my needs. This is the HTML code I attempted: <button type="button" class="btn ...

Organizing Bootstrap Divisions in a Grid Pattern

I can't seem to figure out how to add a right margin to separate these div elements without the second one moving to a new line. It's probably something simple that I'm missing. https://codepen.io/jvern22/pen/GwQpgZ My layout consists of 2 ...

Adjusting website design size when zooming and switching resolutions

<html> <style> body { background-color:#F1EEF2; } header { width:800px; margin-left:auto; margin-right:auto; } layout { min-width: 100%; min-height: 100%; } nav.header { width:800px; height:40px; background-color:#000000; color:#fef8f0; } ...

Transform your standard HTML form code into a condensed single-line embed code

I've devoted countless hours to finding a resolution for this issue. It's most likely simple, but alas, I haven't found it yet. My current project involves creating my own HTML forms using HTML and CSS, along with a touch of JavaScript. In ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Plunker is having trouble locating the angularfire simpleLogin feature

Utilizing Plunker to demonstrate some Angular features, I encountered a frustrating bug displaying the message: failed to instantiate module fireApp due to: [$injector:modulerr] Failed to instantiate module simpleLogin due to: [$injector:nomod] Module &apo ...

I would like to display an update on a button and save it simultaneously

I am facing an issue where I need to add a button that should be able to perform two different actions, update and save. However, despite implementing if-else conditions, it's not functioning as expected. <button type="button" style="float:right" ...

The paragraph tag closes automatically once opened

In the process of establishing a news section on my website, I encountered an issue while using the following code: <p id="news-container"> <h1> . . . </h1> <strong>big</strong> . . . </p> Upon inspecting, it appea ...

Chatting in the hot spring with choices

I am looking to create a customizable dialog box in AngularJS where I can pass options such as title and message based on the caller. Essentially, I want to improve upon the standard alert() function. While the documentation has information on passing par ...

The most effective method for transitioning an application from AngularJS to React-Typescript Micro Frontend

We are in the process of migrating from a monolithic AngularJS App to a ReactJS Micro Frontend App. Our current AngularJS App consists of 64 HTML pages, each rendered based on the API response containing LayoutId. Below is a snippet of the code structure: ...

The Transformicons by Navicon featuring a stylish blue outline

While experimenting with the navicon from sara soueidan, I noticed a blue selector around the icons that I can't seem to get rid of. Is this something specific to the method used, or just a misunderstanding of jQuery? Here is the code snippet: http:/ ...

Leveraging Selenium to extract text from a dynamically populated DIV using JavaScript

I am currently utilizing Selenium to automatically retrieve all comments from a New York Times article. Once the comments are loaded, my goal is to extract them and save the information for future use. However, upon inspecting the source code of the articl ...