Increment the ng-repeat counter with each ng-click event

step-1: Increasing the Todo value with each click on the corresponding todo:

<li class="list-group-item" ng-repeat="todo in todos">
    <span ng-click="count = count + 1" ng-init="count=0"> value= {{count}} </span>
</li>

step-2: How can I access 'count' and the todo's 'id' in my function on each click?

Question (issue here)

my attempt at code (I am aware it is incorrect)

<li class="list-group-item" ng-repeat="todo in todos">
    <span ng-click="addLike(todo._id) (count = count + 1)" ng-init="count=0"> value= {{count}} </span>
</li>

function TodoCtrl($scope) {
  $scope.todos =  [
      {text:'todo one'},
      {text:'todo two', done:false}
  ]
};

Check out the jsfiddle link for more details.

Answer №1

ng-click="count=count+1; addLike(todo._id, count)"

Check out this Fiddle!

Ramya Patel shared some valuable insights on why the increment operator (++) does not function as expected in AngularJS:

When we use ++points in an Angular expression, it leads to an error message highlighting the issue:

Error: [$parse:syntax] Syntax Error: Token '+' is not recognized as a valid primary expression at column 2 of the expression [++points], starting at [+points]

This error indicates that our expression contains unsupported syntax, such as the pre-increment operator ++. The error is generated by Angular's powerful parsing engine, $parse.

Furthermore, each button operates within its own scope, allowing for independent count increments.

Answer №2

The main concept here is to pass your object into the handler and make modifications to it.

var myApp = angular.module('myApp', []);
function TodoCtrl($scope) {
    $scope.todos = [{
        text: 'todo one'
    }, {
        text: 'todo two',
        done: false
    }];
    $scope.likeIt = function likeIt(model) {
        model.count = model.count + 1 || 1;
    }
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <ul ng-controller="TodoCtrl">
        <li class="list-group-item" ng-repeat="todo in todos">{{todo.text}}
            <button class="btn btn-default" ng-click="likeIt(todo)">value- {{todo.count || 0}}</button>
        </li>
    </ul>
</div>

Answer №3

Here is a simple method to achieve this task:

To increment the count, modify the addLike function as shown below:

<li class="list-group-item" ng-repeat="todo in todos">
    <span ng-click="addLike(todo._id,this)"> value= {{todo.count}} </span>
</li>

function TodoCtrl($scope) {
    $scope.todos = [{
        text: 'Task One'
    }, {
        text: 'Task Two',
        done: false
    }]

 $scope.addLike = function(todoid, obj) {
    if (obj.todo.count == undefined) {
        obj.todo.count = 1;
    } else {
        obj.todo.count++;
    }
 }
};

Answer №4

To ensure that the count data persists, it is recommended to delegate this task to a factory:

HTML

<div ng-app="myApp">
   <ul ng-controller="TodoCtrl">
      <li class="list-group-item" ng-repeat="todo in todos">
      {{todo.text}}
    <button class="btn btn-default" ng-click="count(todo)"> value- {{todo.count}} </button>

    </li>
   </ul>
</div>

JS

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

myApp.factory('todosFact', function(){
    var todos =  [
      {text:'task one', count: 0},
      {text:'task two', done:false, count: 0}
    ]
    return todos
})

myApp.controller('TodoCtrl', function(todosFact, $scope){
    $scope.todos = todosFact;
    $scope.count = function count(task){
        task.count++;
        return;
    }    
})

In this code example, $scope is used, but the controllerAs syntax could also be utilized for better organization ()

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

validate that the react functional component exists

I'm new to testing React components, specifically unit testing. I have a React code snippet that is functioning properly, but now I need to write some unit tests for it. My main goal is to ensure that the component is rendering correctly, but I'v ...

Creating a unit test for a directive that includes a link and utilizes a

My current challenge involves unit testing a directive that adjusts form validity based on a controller variable. Here is the code snippet for my directive: angular.module('myModule',[]) .directive('myDirective', function() { ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

Similar to the reference of $(this) in jQuery, there is a similar concept in Vue.js

When working with jQuery, the use of $(this) allows for accessing elements without relying on classes or ids. How can we achieve a similar outcome in Vue.js? ...

Concealing a division at the conclusion of a <section>

Is there a way to toggle the visibility of a div based on scrolling? When reaching section 2; The 'banner' div should appear at the start of section 2 and disappear when section 2 ends. But how can I determine when section 2 is finished in this c ...

Find the sum of every combination of numbers in the array

I've reviewed my code countless times and I'm stumped by the issue. My code is designed to calculate all possible sums of numbers within an array. It works perfectly when there are only 3 numbers in the array, but once I add a fourth number, it i ...

There was an issue compiling the dynamically generated shader in THREE.JS

I am attempting to utilize particles to display falling snow in a 3D scene without creating shaders directly on the HTML page. Due to project constraints, adding specific scripts is not allowed and many additional scripts are loaded dynamically rather than ...

Obtain a collection of custom objects through an HTTP GET request to be utilized in an Angular 2 application

I am currently grappling with the task of efficiently retrieving a list of custom objects and displaying their contents using an HTML file. Here is a simplified version of the HTTP GET method that I am working with: [HttpGet("/atr/testing")] public List& ...

Extracting information from a text field and checking which button was selected, either "yes" or "

Currently, I am exploring JavaScript examples on w3schools and I have a question. Is there a way to retrieve the text entered by the user while also determining if the user clicked OK or Cancel? I understand how to check if OK or Cancel was selected: var ...

retrieve particular content from html following ajax return

Currently, I am in the process of working on ajax functionality where I need to send a request to retrieve data from a specific page. The challenge that I am facing is that the target page contains a complete template with a header, footer, side menu, and ...

Executing the GetDoc function multiple times in a React application

Utilizing Firebase for Authentication & Storage and incorporating useContext from react to encase my application with an authentication layer. After retrieving the user from the authentication layer, I proceed to fetch the user's details from Firesto ...

A missing definition for req.body.object

The issue with the req.body.object variable persists. Even though I have body parser imported, the value remains undefined when I try to console.log() it. //javascript const express = require('express'); var bodyParser = require('body-pa ...

ShallowWrapper is designed to wrap only authentic components - Enzyme for React

While developing a test for a component to assess one of its functions, I encountered an error message stating: ShallowWrapper can only wrap valid elements The relevant component file is named - Panel.jsx (simplified): class Panel extends Component ...

Having trouble getting $compile to work in an injected cshtml file with Angular

Summary I am currently working on a large application where everything is designed to be very generic for easy expansion. One of the components I am focusing on is the dialog. Before suggesting alternatives like using ngInclude or angular templates, let m ...

Tips for ensuring that the toJSON method in Sails.js waits for the find operation to complete before returning the object

When I try to run a find inside the toJSON function in the model, the object is returned before the find completes. How can I ensure that the return happens only after the find operation has completed? toJSON: function() { var obj = this.toObject(); Com ...

Steps for deploying a WaveMaker project without using runtimeLoader.js:

Although WaveMaker is a robust ajax based UI builder, our web service strictly follows a RESTful API standard, making the JSON-RPC API of WaveMaker incompatible with our system. This has led us to explore designing a user interface using WaveMaker without ...

What steps should I take to move the content to the bottom of the page once the promise is fulfilled within the function?

I have a showBoxConfirm function that confirms user actions. After clicking the button, it triggers the clickMethod function. The result variable will store the confirmation response, and if it returns false, the function will terminate. However, the sho ...

JQuery not being recognized by MVC4 view

I encountered an issue with my @Html.DropDownList that is supposed to invoke a jquery function, but it seems that the function is not being called. I've attempted the following: $(document).ready(function () { $('.test').change(function ...

Having trouble retrieving the Node.js file via a POST request

After coming across similar questions without a solution, I am reaching out for help here. I have generated XML content programmatically and displayed it in a Textarea. Now, I need to provide an option for users to export or download this content to their ...

Access information through token-based verification

Just starting out in this area of development, a colleague shared some information with me on how to retrieve the database. I'm feeling a bit lost as to what to do next. curl -X GET -H "Authorization: Token token=xxxxxxxxxxxxxxxxxxxxxxxxx" "https://w ...