What is the best way to increase a counter each time an item in an ng-repeat is clicked?

I have a list created using ng-repeat, with each item containing a count variable. There is also a link in each list item.

My goal is to increase the count when I click on the link.

I attempted the following approach but it did not work as expected.

This is my Controller code:

myApp.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
    var id = $stateParams.id;
    Allposts.GetAllposts(id).then(
        function (response) {
            $scope.allPosts = response.data.posts;
        });

    function ctrl($scope) {
          $scope.increment = function(item){
            item.count += 1;
          }
        }
})

Here is how the view looks like:

<ion-content class="padding" lazy-scroll>
<div class="row no-padding HomeRowsList">

<div class="item itemfull" ng-repeat="post in allPosts">
        <div class="item item-body">
            <div>
                <div class="title-news">
                    <div class="title" ng-bind-html="post.content"></div>
                    <div class="countbg">Number of times: {{post.custom_fields.azkarno}}</div>
                    <span>{{post.count}}</span><a ng-click="increment(post)">Increment</a>
                </div>
            </div>
        </div>
    </div>

</div>
</ion-content>

Answer №1

When working with controllers

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

consider using

function updateCtrl($scope) {
   $scope.updateCount = function(item){
     item.count += 1;
    }
}

and in the HTML file

<span>{{item.count}}</span><a data-ng-click="updateCount(item)">Update Count</a>

instead of

<span>{{item.count}}</span><a onclick="updateCtrl(item);">Update Count</a>

Answer №2

The correct attribute to use is ng-click instead of onclick. The method name should be increment instead of ctrl.

Additionally, it is unnecessary to have the ctrl function wrapper within the increment method. This wrapper is not needed because anything that needs to be called from the HTML should be included in the controller's $scope.

Markup

<span>{{post.count}}</span><a ng-click="increment(post);">Increment</a>

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

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

Nuxt generate encountered a 500 error during execution

My Nuxt app pulls data from a Wordpress REST API, and when I run `nuxt generate`, approximately 100 pages are generated simultaneously. However, around 80% of the API calls made during this process fail with a status 500 error. https://i.sstatic.net/J8975 ...

Issue: Unable to locate the directory containing your Bower packages. Please consider using the --force option to proceed

I am in the process of developing an App with the MEAN Stack and attempting to set up my frontend using yeoman-generator. However, when I run yo angular, the build fails and displays the following message: Running "wiredep:app" (wiredep) task War ...

Customize the appearance of buttons and tabs located in the header section

Front end development is new to me and I'm trying to learn, but I've hit a roadblock. I have 4 components - 2 buttons and 2 tabs that I want to style in a header at the top of the page. Specifically, I want one button on the top left with padding ...

Showing information in Vue.js using v-for loops

I'm currently working on a basic shopping cart system using Laravel and Vue.js. I've been able to add items to the basket and retrieve them successfully up to a certain point, but I'm facing challenges when it comes to displaying these items ...

Error: Attempting to access the 'map' property of an undefined variable, cart

My project consists of two main components, App.js and Cart.js. I am utilizing material-ui and commerce.js API for this application. import React , {useState , useEffect} from 'react' import Products from './Components/Products/Products&apos ...

The bootstrap modal form does not allow for user input of information

For the past few days, I've been encountering a strange bug with Bootstrap Modals that I can't seem to find a solution for online. Any help on this matter would be greatly appreciated. The section of my site that is currently giving me trouble i ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

AngularJS Perspectives: Unveiling the Secrets of Successful Implementation

Do you have any tips on troubleshooting AngularJS views? I found a demo at AngularJS: ngView, but the provided jsfiddle doesn't seem to work. I've been trying to play around with it, but still haven't had any success. This is the code I&apo ...

Is styling in React not showing up?

Currently, I am tackling a third-party pagination component in Reactjs. The npm package instructs me to include the line import "rc-pagination/assets/index.css"; in the file. However, despite injecting the index.css into the DOM using the style loader, I ...

What is the best way to implement CSS for text within a text area?

Is there a way to make the tags dragged from the dropdown list to a text-area non-editable? Currently, the text in the text-area is editable as shown in the GIF. //TextArea HTML Helper @Html.TextAreaFor(m => m.Formula, new { @class = "form-cont ...

Moving the legend around in vue-chartJS

As someone just starting out with Vue-ChartJs, I've become quite intrigued by this: https://i.sstatic.net/j1S0z.png I'm wondering how to move the legend to the bottom of the graph. Can anyone help me with that? ...

Prevent duplication in HTTP POST requests using Express and Node.js

How can I prevent a duplicate object from being created during a post request if the object already exists? I have included my code and JSON object below. I attempted to use next(), but it did not work as expected, resulting in a new object with a differen ...

Troubleshooting Z-Index Problem in Internet Explorer 7 with CSS Dropdown

Despite trying various solutions with JQuery and CSS Tricks, I'm encountering a problem where my drop-down menu won't display properly over my accordion slider in IE7. This issue doesn't appear in other browsers. Any assistance on resolving ...

Customize the appearance of an ASP link button within a navigation menu

Just getting started with ASP.net and CSS, I want to customize my link button using CSS similar to other <a href> buttons, but I seem to be running into some issues. This is the code for my menu: <div id="templatemo_menu"> <ul ...

elasticsearch query for deletion only returns documents that are not found

I have been attempting to use the https://www.npmjs.com/package/elasticsearch-deletebyquery package to delete documents using a query. However, I keep receiving a "Not found" error. Here is my code snippet: client.deleteByQuery({ index: index, type: t ...

Recording the descending data points (excluding the dragged positions) from the bootstrap slider

I am struggling with the implementation of the BootStrap Slider from this source: I have encountered an unusual requirement. I need to capture the values of the slider only when the user stops dragging it, not during the process of sliding. In other words ...

When using Browserify, the function require() on a concatenated string will not include the module in the output script

When using require() to create a combined string path, the path of the module will not be included in the output script. Examples of this include: require("./"+"b" ); //or var path="./"; require(path+"b"); Let's say we have a.js module.exports="a"; ...

Adjust the Height of Angular Material Input Fields

I am looking to adjust the height of the Angular-Material inputs to a minimum level. The reason behind this requirement is that I have to accommodate numerous inputs within a small box (500px in width and positioned at the bottom of the screen). It is cru ...

Python script used to extract data from Vine platform

I am looking to extract post data, such as title, likes, shares, and content, from various brands' public accounts on Vine using Python. Currently, I have a few ideas in mind: There is a Vine API called Vinepy available on GitHub (https://github.c ...