"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here.

var myApp = angular.module('myApp',[]);

var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0},{"name":"three",count:0} ,{"name":"four",count:0}]}

function MyCtrl($scope) {
  $scope.data =jsonInfo;

  $scope.count = function (inc) {
    inc.count =  inc.count + 1
  };
}

Answer №1

If you want to achieve this, you can implement a loop through all items and update the count based on the selected item: increment it for the clicked item and set to 0 for others.

Check out DEMO

var myApp = angular.module('myApp',[]);

var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0},{"name":"three",count:0} ,{"name":"four",count:0}]}

function MyCtrl($scope) {
  $scope.data =jsonInfo;

  $scope.count = function (inc) {
     jsonInfo.count.forEach((item) => {
        item.count = item.name === inc.name? inc.count + 1 : 0; 
     });
  };
}

Answer №2

Give this a shot:

function MyCtrl($scope) {
  $scope.info =jsonData;

  $scope.updateCount = function (item) {

  for(i=0; i<jsonData.count.length; i++){
      if(jsonData.count[i].name != item.name){
      jsonData.count[i].count = 0;
      }
  }
    item.count =  item.count + 1
  };
}

Answer №3

function updateCount(inc) {

    jsonInfo.values.forEach(function(element) {
        if (element.name !== inc.name) {
            element.count = 0;
        }
        return element;
    });
}

$scope.incrementCount = function (inc) {

    updateCount(inc);
    inc.count += 1;
};

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

The input value is displaying one value, but the output is showing a different value

I am encountering a unique issue and could really use some assistance. <input class="testVal" type="number" id="GT_FIRING_TEMPERATURE" value="-17" name="degC" onchange="angular.element(this).scope().unitConversion(value,name, id)"> Despite the valu ...

Issue with displaying selected option from sidemenu in parent view on Ionic 1

1) The main page is named index.html. 2) By default, the router configuration redirects to the login page - template/login.html 3) After a successful login from the login page, users are redirected to the home page that includes a side menu - template ...

Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click. pauseTask: function() { this.isOpen = !this.isOpen; this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume'; }, While it works flawle ...

Building Nested Divs with JavaScript

I've encountered an issue with this code snippet. While it works perfectly fine in jsfiddle, I faced a problem when testing it on my local file. Only the first three lines created by html are displayed: test h1 test h2 test p (I tested the code ...

Body section CSS selector

Can a CSS selector be included within the body section of an HTML document? Here's an example of my code (although it is not functioning as expected): <html> <head> </head> <body> <div style= "a[target=_blank] {backgroun ...

The 'postMessage' operation was unable to be completed on 'DOMWindow' due to a mismatch in the target and recipient window origins provided ('https://outlook.office.com')

Starting off with a functioning MS Outlook web add-in file, the code snippet below sets the groundwork: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> < ...

It appears that the JS function is not being triggered

I am facing an issue with my JavaScript code where a ball is not showing up even though it should. I have an array with only one element, and when that element matches with "F2", the ball is supposed to appear. I suspect there might be a problem with my us ...

The issue with Node module @kenjiuno/msgreader is that it is unable to find the constructor for MsgReader

I've been having trouble getting the example code for parsing Outlook .msg files using @kenjiuno/msgreader to work. Despite successfully installing the module with npm, my code doesn't seem to function as expected: const fs = require('fs&apo ...

Arranging elements on a webpage using Javascript

Creating a Dynamic Div Layout with JavaScript I have successfully implemented functionality wherein clicking on + opens a div and clicking on - closes it. However, I am now faced with the challenge of handling multiple divs at runtime. How can this be ach ...

Using AngularJS to interact with neighboring DOM elements

Imagine a scenario where there is a div containing 5 img elements. When one of these img elements is hovered over, the goal is to change the class of all the elements on its left side. <div id="stars"> <img src="star.png" data-rating="1" ng- ...

Defeat the all-powerful !important tag and enable dialog customization for positioning

I am currently developing a browser extension and I am encountering an issue with using JQueryUI to display a modal dialog. The problem arises when certain websites, for example espn.com, also utilize JQueryUI but do not properly scope their own elements. ...

Utilizing JavaScript to assign class names to dynamically created elements from objects

I specialize in javascript and am working on adding the CSS class .is-slideUp to each card__item element created from a data object, in order to achieve a sliding-up animation effect. Although the .is-slideUp class name appears in the console, it does not ...

Shifting the position of personalized tabs using Jquery

I have created some basic HTML/CSS tabs and I want to move to the next tab by clicking a link at the bottom of every tab. HTML <ul class="tabs"> <li class="active"> <a href="#">Explainer (2mins)</a> <div class=" ...

Looking for a versatile jQuery plugin that enables right-click functionality across different browsers?

I am currently using a context menu plugin that displays a context menu when an element is right-clicked. However, this does not work on elements embedded with ajax. To solve this issue, I am considering utilizing ajax live to trigger the context menu func ...

Can a string or javascript object be uploaded without being saved in a file? - IPFS

I've been exploring the capabilities of js-ipfs API and I'm curious to know if js-ipfs is limited to only uploading files/folders. Is there a way to upload other types of data, such as a JavaScript object like: { heading:"SomeHeading", c ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

The elusive axios was nowhere to be found, not in the project itself nor in any of the directories, including

I am currently working on a mobile app using react native, and I am facing an issue while trying to import Axios. Even though I have installed Axios and everything seems fine, I keep getting the following error: Android Bundling failed 1097ms Unable to r ...

The Laravel Ajax Request is Returning Null

I am faced with a perplexing issue involving a toggle button that should change the status (Show/Hide). Despite sending valid data via ajax and seeing correct data in the console, the request appears empty in the controller. I've made sure to include ...

Mastering the art of implementing ng-if effectively within an ng-repeat that incorporates an orderBy filter and considering the updated scope

My chat message display arranges messages from oldest to newest, with the most recent ones at the bottom. I'm using an ng-repeat on a $scope.messages array, where new chat messages are added dynamically. The orderBy filter is used to sort the messages ...