Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post.

<div ng-repeat="post in posts | orderBy:'-upvotes'">

    <span class="glyphicon glyphicon-thumbs-up"
      ng-click="incrementUpvotes(post)" ng-style="post.hadUpvoted ? {color: 'red'} : {}"></span>
    {{post.upvotes}}

    <span class="glyphicon glyphicon-thumbs-down" ng-click="downvote(post)" 
      ng-style="post.hadDownvoted ? {color:'red'} : {}"></span>

Controller:

var upvoted;
$scope.incrementUpvotes = function(post) {
    if(!upvoted) {
        posts.upvote(post);
        upvoted = true; 
        post.hadUpvoted = true; 
    }
};

Service:

o.upvoteComment = function(post, comment) {
    return $http.put('/posts/' + post._id + '/comments/' + comment._id + '/upvote', null, {
        headers: {Authorization: 'Bearer '+auth.getToken()}
        }).success(function(data) {
            comment.upvotes += 1; 
        });
};

Answer №1

Instead of relying on a global upvoted variable, consider checking it against each individual post.

Your updated controller logic could look something like this:

$scope.incrementUpvotes = function(post) {
    if(!post.alreadyUpvoted) {
        posts.upvote(post);
        post.alreadyUpvoted = true; 
    }
};

The intention here is to maintain an upvoted status specific to each post rather than globally.

I hope this explanation clarifies things. Feel free to ask any questions in the comments section.

Answer №2

upvoted is limited to the entire controller scope, meaning that when you use if(!upvoted), it will not execute if the user has already voted once. To ensure proper functionality, consider using if(!post.hadUpvoted) instead, as this variable is specific to each individual post.

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 global variable is inaccessible when invoked within a dynamically generated function

The variable selected is a global one and accessed using this.selected, which reliably returns the correct value. However, when called from a dynamically created function, it returns unknown. onClick: function(val){ for (i = 0; i < positi ...

Jasmine tests for AngularJS directive failed to invoke the link function

I can't figure out why the link function of my directive isn't being called in a Jasmine test. I've created a simple example to illustrate. Here is the code for my directive (TestDirective.js): 'use strict'; angular.module(&ap ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Swapping mouse cursor using JavaScript

Currently, I am working on a painting application in JavaScript that utilizes the Canvas Object. I would like to customize the mouse cursor when it hovers over the Canvas object. Can anyone advise me on how to accomplish this? ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

Transform an array containing arrays into an array of individual objects

After spending a considerable amount of time trying various solutions, I am still unable to achieve the desired result. The issue lies in getting an array of objects from service calls and organizing them into a single array for data loading purposes. The ...

What is the best way to convert a JSON object back into an object with its own set of methods?

Currently, I have a JavaScript object with multiple methods attached via prototype. When I serialize the object to JSON, only the property values are saved, which is expected. It wouldn't make sense to save the methods as well. Upon deserialization ...

Is it necessary to have required isolated scope attributes in AngularJS Directives?

I'm diving into Angular for the first time and trying to build a directive. I have a question about isolated scope attributes. Say I have this directive: MyApp.directive('myDirective', function() { return { scope: { ...

Troubleshooting issues when testing Angular services using Jasmine and Chutzpah

I've been facing some challenges while attempting to test my AngularJs services with Jasmine as I encounter various errors consistently. In an effort to troubleshoot, I decided to create a simple Sum service for testing purposes but unfortunately, the ...

Tips for assigning a class name to a variable element within a react component?

I am interested in dynamically adding classes to an element. While I am familiar with methods using html-dom and passing a JavaScript expression to className, I am seeking a different approach. Is there a way to add classes similar to pushing them to an ar ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify. I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear whe ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

Is having async as false really detrimental?

Splitting my inquiry into two sections. Within my website, I am dynamically generating some divs by utilizing ajax post requests to retrieve data from the database. Following is the structure of my setup. <html> <body> <script type=" ...

Instructions on setting a flag in AngularJS $resource request and validating it in a global interceptor

Hey everyone, I am working on setting a flag to track requests sent through $resource. To accomplish this, I have created a global interceptor. Does anyone know how I can access and check this flag in both the response and response error of the intercept ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Is there a way to assign retrieved data to the $scope.variable?

I'm relatively new to both JavaScript and Angular. I have a piece of code that fetches data from an API and successfully prints it to the console, but I'm facing issues when trying to assign this data to $scope.saveData. It seems to only work wit ...

The response from the Ajax request in jQuery did not contain any content to download

I have a PHP script that generates PDF output successfully when accessed directly. Now, I want to fetch this PDF file using AJAX. In pure JavaScript, the following code snippet works well: var req = new XMLHttpRequest(); req.open("POST", "./api/pd ...