Ways to update the contents of an individual div within an ng-repeat loop

I am currently working on some Angular code.

<div ng-repeat="item in items | filter:search" class="container">
            <h3>{{item.name}}</h3>
            <p>category:{{item.category}}</p>
            <p>price:INR {{item.price}} /-</p>
            <br/>
            <button ng-hide="showme" ng-click="process(item.name,item.price)">Add</button>
            <button ng-show="showme" class="ng-cloak">Remove</button>
        </div>

What I am trying to achieve is to have a functionality where clicking the add button in a specific div will hide that button and display a remove button. However, I am facing an issue where all the divs are being affected rather than just the one that was clicked.

Below is the code snippet from my controller:

var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
    $http.get('apna.json').success(function (data){
        $scope.items = data;
    });
    $scope.showme=false;
    $scope.process = function(name, value){
        $scope.total = parseInt($scope.total) + parseInt(value);
        $scope.showme = true;
    }
});

Answer №1

To add visibility functionality to your items, include a display property in the items array and set it to false. Use item.display in ng-show and ng-hide directives. Also, update the display variable within the process() function for that specific item.

Answer №2

Your showme variable is stored on $scope, meaning each item does not receive a new showme variable or property to store its specific setting. Instead of assigning it to $scope, you can create a new property on the item itself to indicate whether it has been added or not. This property can then be used to toggle the visibility using ng-show/ng-hide directives.

<button ng-hide="item.added" ng-click="process(item)">Add</button>
<button ng-show="item.added" class="ng-cloak">Remove</button>

In your process method:

item.added = true;

Check out the demo below:

var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
    $scope.items = [
      {name:"Item 1",category:"food",price:19},
      {name:"Item 2",category:"auto",price:39},
      {name:"Item 3",category:"software",price:13}
    ];
    $scope.total = 0;
    $scope.process = function(item){
        $scope.total = parseInt($scope.total) + parseInt(item.price);
        item.added = true;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="restaurantController">
  Total: {{total}}<br>
  <div ng-repeat="item in items | filter:search" class="container">
    <h3>{{item.name}}</h3>
    <p>category:{{item.category}}</p>
    <p>price:INR {{item.price}} /-</p>
    <br/>
    <button ng-hide="item.added" ng-click="process(item)">Add</button>
    <button ng-show="item.added" class="ng-cloak">Remove</button>
  </div>
</div>

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

A basic structure for a JSON array

Perhaps my next question may appear silly, but I'll ask it anyway :) Here is the structure in question: { "name": "Erjet Malaj", "first_name": "Erjet", "work": [ { "employer": { "id": "110108059015688 ...

Retrieve the <style> tag response and inject it into the head section of the HTML using React

Although I am aware that this may not be the best practice, it seems to be the most suitable solution for this particular case. The server response contains something like this: <style id="styles">.color_txt{color:green;}</style> I am attempt ...

Attempting to retrieve data from the Model in a JavaScript function post-page render using NodeJS and EJS

I'm new to NodeJS and I'm working on my first application. I am using Ejs to create the user interface and passing a model with data displayed in a table. I'm attempting to access this model's data in a JavaScript function to avoid ano ...

creating a personalized dropdown menu with react javascript

Is it possible to create a chip in a single select dropdown in React? In a multi-select dropdown, a chip is created as shown in the example below. Can we achieve the same effect in a single selection dropdown? const DropdownExampleClearableMultiple = () = ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

What is the best way to access all of a class's properties in JavaScript?

Is there a way to retrieve all the properties of a class using JavaScript? For example, if I have a class like this: .menu { color: black; width: 10px; } How can I extract "color: black; width: 10px;" as a string using JavaScript? Thanks in advance! ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

Refresh the pagination in a jQuery DataTable

I have incorporated DataTable for pagination within my table. The data in the table is loaded through ajax requests, and I am utilizing my custom functions to populate the table manually by interacting with its DOM elements. However, I am facing an issue ...

Using Angular JS to redirect in an Express JS application

When using AngularJS, I make an http get request like this: $http.get('/api/users?id='+userID) If the request is unauthorized, I redirect with a status code from ExpressJS like this: res.status(401).location('/login').end(); But for ...

Dealing with Errors in AngularJS $resource Using Callbacks

I have a factory that offers various services for fetching data from a custom API I created. All the callbacks are functioning correctly, but I am interested in implementing error handling during the fetch process. .factory('customApiService', f ...

Having trouble getting an AjaxBeginForm to function properly within a JQuery script on a PartialView

Within the main controller view, we bring in the partial view utilizing the following code: @Html.Partial("MapPartial", Model) Within the Partial View, I aim to display a map. Currently, there is an Ajax beginform with a submit button that ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Adding a new value to an array of objects without altering the existing values in ReactJS and NextJS

I have a JSON file containing image names that I need to organize into a Key-Value Object. I am currently using regex to create keys by removing "-img[image No]". However, I am having trouble storing all the image names in the array without overwriting pre ...

Javascript malfunctioning - exhausted all troubleshooting options

My JavaScript code consists of a single line, but I keep encountering the "getElementById null" error. document.getElementById("menu-background").style.left = "0"; HTML: <html> <head> <title></title> <link rel="style ...

Control the button's activation status by accepting or unaccepting the two checkbox conditions

In my search through stackoverflow for help on enabling/disabling a button conditionally, I found some assistance but nothing quite matched what I needed. My situation involves two checkbox conditions rather than just one. The button should only be enable ...

What is the best method to assign a property to a model within AngularJS by utilizing an attribute parameter?

I am in the process of creating a custom directive in AngularJS for a UI slider that can be used multiple times. Each slider should be able to bind to a specific property. My idea was to use an attribute called "property" which would automatically update w ...

JavaScript - Two tables shown in parallel

Beginner coder seeking assistance! I am currently working on an application with two user input fields placed adjacent to each other. Clicking parse buttons next to these fields generates two separate tables. However, I need these tables to be displayed si ...

Show JSON information from a jQuery post request

Greetings, I am currently working on implementing a login script using Ajax. My objective is to retrieve and display data such as email and username, and then store it in local storage. Although I can successfully obtain the data in JSON format, I want to ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

What could be causing the issue of the view not showing up in AngularJS?

I've been trying to use AngularJS modules to display a view, but for some reason my page isn't showing up. Can anyone help me figure out what's going on? You can check out my code at the following link: <!DOCTYPE html> <html> & ...