Implementing distinct click tracking with AngularJS

var app = angular.module('app', []);
app.directive("eventsEvaluation", function() {
  return {
    restrict: "E",
    template: "<div>" +
      "<span class='span' type='number' data-ng-bind='number'></span>" +
      " <a class='btn btn-default' href='#' data-ng-click='reduce()'><span class='glyphicon glyphicon-minus'></span></a> " +
      " <a class='btn btn-default' href='#' data-ng-click='increase()'><span class='glyphicon glyphicon-plus'></span></a> " +
      "</div>",
    replace: true,
    transclude: false,
    controller: function($scope) {
      $scope.number = 0;
      $scope.increase = function() {
        $scope.number++;
      };
      $scope.reduce = function() {
        $scope.number--;
      };
    },
  }
});
span.span {
  width: 40px;
  height: 40px;
  display: block;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container" data-ng-app="app">
  <form>
    <h3>Choose your preference</h3>
    <div class="row">
      <div class="col-md-4">
        <events-evaluation data-ng-model="number">
        </events-evaluation>
      </div>
    </div>
    <h3>Choose your preference</h3>
    <div class="row">
      <div class="col-md-4">
        <events-evaluation data-ng-model="number">
        </events-evaluation>
      </div>
    </div>
  </form>
</div>

I am seeking a code for a like/dislike system, but I am facing some difficulties. First: How can I make $this in Angular behave similarly to jQuery, because currently, if I click the plus button in the first section, the plus button in the second section is also clicked. I want the clicks to be separate for each section.

Second: How can I ensure that only one click is allowed for plus or minus (i.e., the click range should be limited to 1)?

Answer №1

Ensure that both ng-models are referencing different $scopes. You can achieve this by assigning different $scopes in ng-model as shown below.

var app = angular.module('app', []);
app.directive("eventsEvaluation", function () {
return {
restrict: "E",
template:
"<div>" +
"<span class='span' type='number' data-ng-bind='number'></span>" +
" <a class='btn btn-default' href='#' data-ng-click='reduce()'><span class='glyphicon glyphicon-minus'></span></a> " +
" <a class='btn btn-default' href='#' data-ng-click='increase()'><span class='glyphicon glyphicon-plus'></span></a> "+ 
"</div>",
replace: true,
transclude: false,
controller: function ($scope) {

$scope.quetions = [      
      {ques:"Angular 2 is same as react js?", qno : 1},
      {ques:"What is Angular 2?", qno : 2}
    ]

$scope.number = 0;
$scope.increase = function () {
$scope.number++;
};
$scope.reduce = function () {
$scope.number--;
};
},
}
});
span.span
{
width:40px;
height:40px;
display:block;
font-size:20px;
font-weight:bold;
text-align:center;
margin-left:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container" data-ng-app="app">
<form>
<div class="row">
<h2>See here:</h2>
<div ng-repeat="q in quetions">
<events-evaluation class="col-md-6" data-ng-model="q.qno">
</events-evaluation>
<p class="col-md-6">{{q.ques}}</p><br>
</div>
</div>


<h2>See yours:</h2>
<h3>Like or dislike</h3>
<div class="row">
<div class="col-md-4">
<events-evaluation data-ng-model="number">
</events-evaluation>
</div>
</div>
<h3>Like or dislike</h3>
<div class="row">
<div class="col-md-4">
<events-evaluation data-ng-model="number">
</events-evaluation>
</div>
</div>


</form>
</div>

Answer №2

It is important that the values are controlled by an external controller rather than the directive itself.

To track changes in the external controller values, I have included a 'Log Values' button.

var app = angular.module('app', []);
app.controller('MyController', function($scope) {
  $scope.number1 = 1;
  $scope.number2 = 0;
  $scope.log = function(){
    console.log($scope.number1, $scope.number2);
  }
});
app.directive("eventsEvaluation", function() {
  return {
    restrict: "E",
    template: "<div>" +
      "<span class='span' type='number' data-ng-bind='value'></span>" +
      " <a class='btn btn-default' href='#' data-ng-click='reduce()'><span class='glyphicon glyphicon-minus'></span></a> " +
      " <a class='btn btn-default' href='#' data-ng-click='increase()'><span class='glyphicon glyphicon-plus'></span></a> " +
      "</div>",
    replace: true,
    transclude: false,
    scope: {
      value: '=',
    },
    replace: true,
    link: function($scope, elem, attr, ctrl) {

      $scope.increase = function(val) {
        $scope.value++;
      };
      $scope.reduce = function(val) {
        $scope.value--;
      };

    }
  }
});
span.span {
  width: 40px;
  height: 40px;
  display: block;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container" data-ng-app="app">
  <form ng-controller="MyController">
    <h3>Like or dislike</h3>
    <div class="row">
      <div class="col-md-4">
        <events-evaluation value="number1">
        </events-evaluation>
      </div>
    </div>
    <h3>Like or dislike</h3>
    <div class="row">
      <div class="col-md-4">
        <events-evaluation value="number2">
        </events-evaluation>
      </div>
    </div>
    <button type="button" ng-click="log()">Log Values</button>
  </form>
</div>

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

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Displaying selected checkbox values in a URL with parameters using PHP and JavaScript

I am looking to extract the selected checkbox value and append it to the browser URL with a parameter name. Below is my HTML code: <div style="width:200px; float:left"> Price <div> <input type="checkbox" name="price" value="0-1 ...

Unexpected element layout issues

Attempting to create a basic website that utilizes the flickr api, retrieves photos and details, and displays them using bootstrap. However, there seems to be an issue that I am unsure how to resolve. Currently, my code is functioning like so: https://i.s ...

The most effective method for modifying a prop in VueJS without altering the parent's data

In the main Vue component, there is an object named user. If I pass this user object as a prop to a child component: <child :user="user"></child> When updating user.name in the child component, the changes also reflect in the parent componen ...

Aggregate the values in each position across various arrays and merge them into distinct arrays

I'm facing an issue that I can't seem to solve on my own. Imagine we have several arrays: [1,2,3] [1,2,3] [11,12,13] How do I go about extracting all the values at each index from these multiple arrays and combining them into separate arrays? T ...

While iterating through the material-ui rating component, the 'index' value remains constant at 0 within the 'onChange' function

For my e-commerce React.js web app, I want to show the rating value of each product. Using the JS map function, I was able to track which product was hovered by its index ('onChangeActive' is the handler for this). {products.map((product, index) ...

Issue with Ajax reappearing the second time

Currently, I am experiencing an issue with the sorting function on search results. After performing a search, if I try to change the value in the dropdown for filtering the number of results per page, it works fine for the first time. However, upon further ...

When trying to arrange the intelligent table, it triggers a fresh ajax request

I am currently using an Angular.js smart table that retrieves data from an Ajax call using $resource. I have implemented st-pipe to specify the ajax function and I'm utilizing st-safe-src. Upon initialization, the smart table successfully completes t ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

Executing a JavaScript function with jQuery

function launch() { $("p").text("Hey there", greet()); } function greet() { alert("Greetings! You have triggered another function"); } HTML: <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button onclic ...

AngularJS 1.7.8 causing compatibility issues with angular-ui-bootstrap 2.5.6

Currently delving into AngularJS, I am striving to transform a project that originally operated on regular Javascript, jQuery, and Bootstrap framework into an AngularJS single-page endeavor while still incorporating the Bootstrap library. Following the pro ...

Learn how to creatively style buttons with dynamic effects using tailwindcss

My Desired Button: I have a Button component that can accept a variant prop. My goal is to have the button's className change dynamically based on the prop passed to it. Instead of using if/else statements for different buttons, I want to use a sing ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

Navigating to the present child state with modified parameters can be achieved using the following steps

Check out this demo: https://jsfiddle.net/explorer/622qzqsc/ In the platform I'm working on, we have an advanced concept of state management, specifically for building timelines. In the template of this system, there's a code snippet (which is c ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Functionality Issue: Submit Button Not Working on Designed Form Select

Through dedication and hard work, I managed to create a customized form with images that display correctly in Firefox, Chrome, and Internet Explorer's compatibility mode. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...

ngModel.$setValidity is a one-time operation

Currently, I am working on a validation issue with an angular bootstrap ui datepicker popup. I have set the max and min dates for validation, which work when the user selects a date from the calendar. However, if the user manually inputs a date, these vali ...

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

If I am already in the child router and attempt to refresh the browser, I will not be able to load

This is a custom router configuration for student enrollment. var studentEnroll = { name: 'student-enrollment', label: "Enroll Student", url: '^/home/students/enroll', par ...