How to toggle button states within an ng-repeat loop in AngularJS

    <div ng-repeat="item in Items">                          
       <button ng-init="checkIfDisabled[item.name] = true" 
ng-disabled ="checkIfDisabled[item.name] ===true "></button>
                        </div>

In my project, I am working with a variable called cart that contains objects. The objective is to have the button enabled only if any of the objects in the cart variable match the item being displayed on the page.

When adding items to the cart, this code snippet was used:

 var itemname = item.name;
  $rootScope.checkIfDisabled[itemname] = false;

However, it seems this approach is not achieving the desired outcome. Is there an alternative solution?

The buttons are initially disabled but remain so even after the value changes to false.

Answer №1

In order to manage cart items, you should create an array to store them and then implement conditions to control their enable/disable status.

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.Items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    $scope.cartItems = [];
    $scope.addToCart = function(item) {
      $scope.cartItems.push(item);
    };
    $scope.doesExist = function(item) {
      return $scope.cartItems.indexOf(item) !== -1;
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="js/angular.min.js"></script>
</head>

<body ng-controller="myController">
  <div ng-repeat="item in Items">
    <button ng-disabled="doesExist(item)" ng-bind="item" ng-click="addToCart(item)"></button>
    <br/>
    <br/>
  </div>
</body>

</html>

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

Tips for effectively training my Neural Network

I am currently working on training a neural network to determine directional decisions based on its inputted life level. The neural network is designed to take in three inputs: [x, y, life]. If life => 0.2, it should output the angle from [x, y] to (1, ...

Creating an ImmutableJS Record with custom types: A step-by-step guide

Is there a way to make ImmutableJS Records throw runtime exceptions if fields are missing instead of needing default values? ...

Interference of setInterval with other setInterval functions

Attempting to set up multiple setInterval functions and store them (for later clearing) results in the last setInterval overriding the previous ones. This causes each interval to execute only once, with the same output. Below is a code snippet demonstrati ...

I need help figuring out how to get a horizontal scrollbar positioned at the top of a div to function properly once the content has been loaded using ajax

HTML CODE <div id="scrollidout" style="overflow: auto; overflow-y: hidden; "> <div id="scrollidin" style="padding-top: 1px; height: 20px; width: 1000px">&nbsp;</div> </div> <div class="resultcontent" style="overflow ...

Share an entire /folder through an express server

I am currently working on an express server setup, and I am looking to streamline my route handling for managing an entire directory structure. root /html /css /js /app.js /images /index.html /some-other.htm ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Experiencing complications when retrieving API information in my React component

There is a json file available: {"area":[{"id":"1","name":"abc","address":"223 "},{"id":"2","name":"xyz","address":"123 "}] I am trying to fetch and display the data in my component using react and redux. Although I have successfully loaded the url with ...

The AngularJS Factory retrieves stale data after the initial API call without contacting the server and functions within a nested sticky state

I've been struggling with this issue for days and can't seem to find a solution... Here's how my route is set up: $stateProvider.state({ name: 'core.portfolio', url: '/portfolio', c ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

Unable to invoke extension method on parent class in TypeScript

Wondering about classes and extensions in TypeScript? Let's take a look at an example: We have a base class called Report, with another class named Datasheet that extends from Report. An extension has been added to the Report class, and the goal is ...

Deactivate a particular function key with the help of jQuery

Is there a way to disable the F8 key on a web page using jquery, plugins, or just javascript? Thank you in advance! :) blasteralfred ...

Developing a versatile code block for handling animations within my project

As I delve into learning jQuery to enhance my new website, I realize that my expertise lies more in web design rather than programming. I find myself struggling to create a versatile function that can be applied to multiple div elements within the HTML. B ...

My navigation menu has a nested ul, but on mobile devices, it doesn't display all the items in the list. What could be causing

When I click on "Products" in my main navigation, only the first 6 items are displayed from a nested ul. How can I make all of them display when the user clicks on "Products"? Is this a CSS issue or a problem with the script? Here's a screenshot for r ...

Creating PDFs with barcodes using Node.js

Currently, I am utilizing https://github.com/devongovett/pdfkit to create PDF files easily. This can be achieved with a simple code snippet like below: app.get('/get-pdf', (req, res) => { const doc = new PDFDocument(); const filename = &ap ...

Managing and Streaming Music in a Rails Application

Currently, I am storing mp3s using paperclip and they only play back if I utilize Amazon S3. However, I am hesitant to use Amazon S3 because I am unsure how to secure the files. Now, I am reconsidering my approach as I need to secure the mp3s and provide ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

Using the hide() method in jQuery will automatically reset the value

When using the jQuery .hide() function to hide an input by ID, I am wondering if it resets the field/select value to [0], val(''), or empty, etc. My concern is that if a user populates a field, then decides to hide it due to a show/hide condition ...

GIF Embeds with a Discord.js Bot

My bot is currently sending random gifs, but they are not embedded. I would like to send random gifs with embeds instead. How can I achieve this? Here are the codes: if (msg.author.bot) return; if (msg.content.toLowerCase() === prefix + 'xgif&ap ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Showcasing local storage data in a textarea using React hooks

I am currently developing a note taking application using React. Successfully implemented state management with local storage. The objective is to display the 'notes' from local storage in the textarea upon rendering and refreshing. Currently, ...