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

adjusting the color of ion-button when hovering over the cancel button

I'm working on a button bar for my app and I want the color of the button to change based on its state (false, true). Currently, the button starts out green, turns light green when hovered over, and becomes white when clicked. Once I click it, the bu ...

Adding an AngularJS directive dynamically that utilizes a $http request for fetching data

Currently facing an intriguing issue, I am attempting to create something like this: input key 1 , input value 1 input key 2 , input value 2 < button to add more > < submit button > Essentially, a user can click submit and send a Get req ...

Provide the aggregated content within d3's text() or html() function

Below is my d3 code snippet: grouping.append('foreignObject').html(function (d) { var string = '<p>hello, {{ "there" }} <some-directive></some-directive></p>'; string = $compile(string)(scope); return stri ...

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

Executing the command "node <app name>" does not result in any action

I am experiencing an issue with my bot app called "vgen.js". When I run the command "node vgen", the prompt/directory disappears and the cursor just blinks on the far left of the screen. I have been following instructions from a tutorial found here: https ...

Is there a way to export the HTML table content to an Excel sheet that is compatible with browsers such as Internet Explorer, Mozilla Firefox, and others?

Welcome to my HTML Page! <html> <head> <title>Table </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> </script> </head> <body> <table ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

Checking for the presence of the key name "item[]" within an object in AngularJs

I currently have an object called "obj" with two keys: "goal" and "item[]". It looks like this: var obj = {goal:"abc",item[]:"def"}; These keys and values are dynamically generated. Now here's the problem - I need to determine if these keys exist ...

Generating references dynamically without the use of strings

UPDATE: Our current React version is 16.2.0, which is important for this question (check out this answer). From what I understand, this is the recommended way to create a ref in our React version: <div ref={(r) => { this.theRef = r; }}>Hello!< ...

Is there a way to retrieve the list of files from a static public folder using javascript?

I have successfully set up a public folder directory using express and node. For instance, this code works perfectly - var testImage = new Image(); testImage.src = '/images/png/avatar.png'; However, I need to access several images stored ins ...

What is the best way to close all modal dialogs in AngularJS?

Back in the day, I utilized the following link for the old version of angular bootstrap: https://angular-ui.github.io/bootstrap/#/modal var myApp = angular.module('app', []).run(function($rootScope, $modalStack) { $modalStack. dismissAll( ...

Issues encountered during the installation of Electron JS

Having trouble installing electronjs in Node.js 18 LTS and NPM 10? Getting an error message like this? PS C:\Users\Administrator.GWNR71517\Desktop\electron> npm install electron --save-dev npm ERR! code 1 npm ERR! path C:\Users& ...

Leveraging the 'passport.isAuthenticated()' method for evaluating numerous user roles within a Node.js application

Below is the code snippet for my custom isAuthenticated function: var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }; Here's a route that uses PassportJs with the custom isA ...

Exploring the 3D Carousel Effect with jQuery

After creating a 3D carousel using jQuery and CSS3, I am looking to enhance it with swiping support. While there are plenty of libraries available for detecting swipes, I specifically want the carousel to start rotating slowly when the user swipes slowly. ...

The `process` variable is not recognized in a Vue/TypeScript component

I've encountered an issue trying to use .env variables in my Vue app. When I ran npm install process, the only syntax that didn't result in an error when importing was: import * as process from 'process'; Prior to this, I received the ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Why isn't my onClick event functioning as expected?

I used the handleClick function in an onClick event, but it's showing an error (this is not defined). var Buttons = React.createClass({ getInitialState() { return { field: ':P ' } }, handleClick(field ...

Error 404 encountered when updating packages in Angular2 tutorial: platform-browser-dynamic.umd.js

I recently started following an Angular2 tutorial, but upon returning to it and reaching the Routing chapter, I realized that the tutorial had been slightly updated. This required me to go back and update the package.json file to match the current version, ...