Can a single vote in AngularJs be limited to just one up or down option?

During a lesson on AngularJS from Code Academy, the following code was presented. The lesson included a rating system where users could choose to 'like' or 'dislike' an item. Clicking the 'like' button would increase the vote count, while clicking 'dislike' would decrease it. However, the code does not include a way to limit a user's voting to only once. Is there a method in AngularJS to restrict user voting to just one instance?

Sample HTML code:

<div class="rating">
        <p class="likes" ng-click="plusOne($index)">+{{product.likes}}</p>
        <p class="dislikes" ng-click="minusOne($index)">-{{product.dislikes}}</p>
</div>

AngularJS code:

app.controller('MainController', ['$scope',
  function($scope) {
    $scope.title = 'Top Sellers in Books in this Great City';
    $scope.promo = 'Our Christmas Promo is on the way!';
    $scope.products = [{
      name: 'The Book of Trees',
      price: 19,
      pubdate: new Date('2014', '03', '08'),
      cover: 'img/the-book-of-trees.jpg',
      likes: 0,
      dislikes: 0
    }, {
      name: 'Program or be Programmed',
      price: 8,
      pubdate: new Date('2013', '08', '01'),
      cover: 'img/program-or-be-programmed.jpg',
      likes: 0,
      dislikes: 0
    }, {
      name: 'Book1',
      price: 8,
      pubdate: new Date('2015', '04', '02'),
      cover: 'img/..',
      likes: 0,
      dislikes: 0
    }, {
      name: 'Book2',
      price: 8,
      pubdate: new Date('2015', '09', '09'),
      cover: 'img/..',
      likes: 0,
      dislikes: 0
    }];
    $scope.plusOne = function(index) {
      $scope.products[index].likes += 1;
    };
    $scope.minusOne = function(index) {
      $scope.products[index].dislikes += 1;
    };
  }
]);

Answer №1

A simple way to implement voting functionality is by manipulating the object inside an array.

$scope.plusOne = function(index) {
    if(!$scope.products[index].upvoted){
      $scope.products[index].likes += 1;
      $scope.products[index].upvoted = true;
    }
};
$scope.minusOne = function(index) {
    if(!$scope.products[index].downvoted){
      $scope.products[index].dislikes += 1;
      $scope.products[index].downvoted = true;
    }
};

If you want to handle scenarios where an upvote cancels a downvote (or vice versa), a few more lines of code will do the trick.

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 URL redirect is malfunctioning and prompting an error stating "No 'Access-Control-Allow-Origin' header"

Having trouble sending an Ajax request to a Node.js server from my application and encountering the following error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the ...

View hyperlinks within a designated DIV container

I have a menu wrapped in a DIV element and I want to open the links from the menu in another DIV called TEST. So far, the only method I've found is using an iframe, but I'm looking for another solution, possibly with JavaScript (without using AJA ...

Generate sequential keys for objects in an array

Looking for assistance; Imagine I have an array of objects structured like so { 'Name:'ABC', 'Code': 'BP' } What is the most effective method to add an incremental attribute to this array in typescript. [{&apo ...

Can you list out the directives that are responsible for generating child scopes in AngularJS?

I recently discovered that when using ng-if, it actually creates a child scope, leading to some confusion on my end. I'm curious about the reasons or benefits behind ng-if's scope creation. Can you also tell me which other built-in directives cre ...

Utilizing Angular to make API requests and handle promises

Currently, I am facing a challenge in my angular application which involves working with the soundcloud api. The issue arises when I make a call to the soundcloud api to retrieve my tracks, loop through them to extract the iframe embed object, inject it in ...

fetch() operates successfully in Extension but encounters difficulties in Chrome Console/Snippet

I am currently facing an issue with my Chrome Extension. The extension performs a successful GET request, but when I try to replicate the same action in the Chrome Console or Snippets, I encounter errors. Here is a minimal example of the code I am using: f ...

Two synchronized checkboxes working in unison

Is there a way to synchronize two checkboxes on a page so that when one is selected, the other is automatically selected as well, and vice versa? I've been able to select both checkboxes simultaneously, but I'm struggling to find a way to deselec ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Accessing the outer index in a nested loop using Handlebars

Imagine I have the code below: <div> {{#each questions}} <div id="question_{{@index}}"> {{#each this.answers}} <div id="answer_{{howToGetThisIndex}}_{{@index}}"> {{this}} </div> {{/each}} </div> ...

How can I use jQuery to display a div alongside the element that is currently being hovered over?

Imagine having multiple divs similar to these: UPDATE: <div class="ProfilePic"> <a href="#"> <img src="lib/css/img/profile_pic1.png" alt="" class="ProfilePicImg"/> </a> <div class="PopupBox" style="display: ...

Exploring the playful side of DPI evaluation

I have a function that adjusts the size of an image based on the window.devicePixelRatio. Now, I am looking to properly test it. const wrapper = mount(myComponent, { propsData: { size: { height: 500, width: 500, }, f ...

Developing a custom Jquery UI modal with inactive buttons

Is there a way to open the dialog box with the buttons disabled and grayed out? $("#battleWindow").dialog({//open battling window title: "Battle!", closeOnEscape: false, modal: true, width: 500, buttons:[{ text: "Cast", ...

NodeJS serving mp3 files to enhance audio tags

I am running into issues when trying to serve mp3 files using NodeJS. var filestream = fs.createReadStream('file.mp3'); filestream.on('open', function() { var stats = fs.statSync('file.mp3'); var fileSizeInBytes = stats[" ...

Is polymer routing the best choice for large-scale websites?

I am currently working on a large project that consists of various layouts and structures, totaling around 100 different pages. Despite the variations in content, the core elements such as headers and menus remain consistent throughout. To streamline my ...

How to utilize PHP $_SESSION variables with jQuery for error handling and page redirections

I am currently working on a project where I need to access PHP session variables using jQuery in order to redirect users using jQuery instead of PHP. When a user logs in, a PHP script is executed to check their logged in and registered status in the databa ...

The refusal to run JavaScript stemmed from an empty MIME type, resulting from the combination of nodeJS, express, engintron, and nginx

Currently, I'm struggling with a frustrating issue that's making me want to pull my hair out. So, here's some important information you need to be aware of: My application is built using node.js (version 16.13.1) with express and nginx man ...

Testing Angular Factory Injection functionality

I have come across similar issues but haven't found a solution that works for my situation. The error message Error: [ng:areq] Argument 'fn' is not a function, got undefined is causing my test to fail. How can I properly inject a factory int ...

Display loading screen during the setup of the main page

Is there a way to display a preload image while the main page is being prepared and loaded, without using Ajax? I need to reload the entire main page, so I'm considering the following approach: First, request the preload page from the server. Second, ...

Angular Components unexpectedly lose background transparency when using Transparent-Background-PNG in the foreground

Hey there! I'm currently working on a landing page and I have this amazing idea to use a stunning picture of clouds with a transparent background layered over a beautiful landscape. The only problem is that when I try to implement it, the transparency ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...