AngularJS function for alternating addition and subtraction operations

I am looking to create a toggle button that will add money to a total price when clicked once, and subtract that amount when clicked again to "deselect" it.

Currently, I have this HTML code that toggles between adding and removing a class to change the background color of the selected button -

<div class="col-md-4" ng-repeat="service in services_data track by $index">
      <div ng-class="showDetails[$index] ? 'panel-warning': 'panel-default'" class="panel">
        <button ng-click="$parent.showDetails[$index] = !$parent.showDetails[$index]; price(service.price, service.est_time_mins)" class="panel-heading btn"><span class="pull-left badge">$ {{service.price}}</span>{{service.name}}</button>
        <div class="panel-body">
         {{service.est_time_mins}} mins. {{service.style}}  
        </div>
      </div>
  </div>

In addition, here is the corresponding controller code -

app.controller('AppointmentController', ['$scope','services', function($scope, services) {
var data = {};
data.fn = 'services';
services.getData(data).success(function(return_data){
  console.log(return_data);
  $scope.services_data = return_data;
});
var data = {};
data.fn = 'get_barbers';
services.getData(data).success(function(rd){
  $scope.barbers = rd;
  console.log(rd);
});
$scope.total_price = 0;
$scope.time = 0;
$scope.price = function(price, time){
  $scope.total_price = parseInt(price) + parseInt($scope.total_price);
  $scope.time = parseInt(time) + parseInt($scope.time);
} 
}]);

I hope this explains everything clearly. Thank you for your assistance.

Answer №1

Implementing a boolean flag technique:

$scope.selected = false;
$scope.updateTotalPrice = function(price) {
    //Subtract price if item is currently selected
    if ($scope.selected) $scope.total_price -= price;
    //Add price if item is currently NOT selected
    else $scope.total_price += price;
    $scope.selected = !$scope.selected; //Toggle selection status
};

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

Filtering the values of an array nested within objects

Imagine having a vast database of 10,000 cards and attempting to filter them based on the banlist_info.ban_ocg === "Forbidden" { id: 15341821, name: 'Dandylion', type: 'Effect Monster', desc: 'If this card is sen ...

Angular-leaflet-directive marker management

Is there a way to retrieve the handle of a marker so that I can set the icon when a ng-mouseover event occurs somewhere else on the page? In Leaflet, I add my markers like this: angular.extend($scope, {markers: {'id1': {lat:foo, l ...

Converting a standard redux object into a format suitable for display

Working on a React Native project with Redux, I need guidance on transforming data for rendering purposes. The data structure I have is a normalized object called userDetails, which looks like this: "userDetails": Object { "allIds": ...

Page showing without banner

As I scroll down through my website, I want a specific banner to appear when I reach the contact page. The banner will show a goodbye message and give users the option to close it or keep it open. For example: (function() { requestAnimationFrame(fu ...

Determine the number of stored values in a specific key by utilizing stringify within localstorage

Is there a way to determine the number of unique values stored under one key in local storage? For instance: Here is the content of my local storage: [{"id":"item-1","icon":"google.com"},{"id":"item-2","icon":"youtube.com"}] In this case, I would like ...

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

Unable to perform cross-browser testing on Internet Explorer 11 using Protractor JS

I am looking to conduct cross-browser testing using Selenium on Node.JS with Protractor 2.0. While the instances of FF & Chrome are working fine, there seems to be an issue with IE11 not opening. Upon attempting to run it, I encountered the following err ...

When an absolute positioned DIV is nested inside a relatively positioned DIV, it disappears when the page is scrolled

A unique feature of my DIV is that it remains fixed at the top of the page as you scroll. This is achieved by setting its position to fixed. However, within this main container, I have another div with a relative position. While the content in the relative ...

The v-model of one component causing interference with the v-model of another component

I am currently utilizing vue js alongside buefy and have implemented two components: a field-radiobox component and a field-textarea component. Within my post.cshtml page, I can choose an option from the radio buttons, and the selected value is appropriat ...

What is the best method for retrieving a child control from a TR element?

I am facing an issue with a hidden field inside each Tr in my template: <ItemTemplate> <tr style="" class="ui-selectee trClass ui-widget-content"> <td style="width: 100px"> <asp:HiddenField ID="idField" runat=" ...

getJSON takes precedence over other tasks

I am having a challenge retrieving data in JSON format from the server and displaying it dynamically in a table. The code runs without errors and successfully fetches the data, but for some reason, nothing appears in the table. I suspect there may be an ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Can the functionality of two-way data binding be achieved in Angular without utilizing ng-model and ng-bind?

During an interview, I was presented with this question which sparked my curiosity. While I have a foundational understanding of AngularJS and its ability to enable two-way data binding using ng-model and ng-bind, I am interested in exploring alternative ...

Learn the Method Used by Digg to Eliminate "&x=0&y=0" from their Search Results URL

Instead of using a regular submit button, I have implemented an image as the submit button for my search form: <input id="search" type="image" alt="Search" src="/images/searchButton.png" name="" /> However, I encountered an issue in Chrome and Fire ...

Is there a way to retrieve the productName or productId associated with the error image when the image triggers an onerror event?

Hello, I am a beginner when it comes to AngularJS. I am attempting to retrieve the name of the product or product id if the image for that particular product fails to load in the <img> tag. This way, I can perform certain actions using that productId ...

A guide for finding a specific string within a subset of an array

I have an array containing various substrings, and I want to pass if at least one of those substrings contains the specific value I am searching for. Value1 = [ "Grape | 100 |Food Catering Service", "Apple | 100,000m |Food Catering Servi ...

Slight Misalignment of Elements

I am attempting to align two corners of an element so that they perfectly match the corners of another element. In simpler terms, I am aiming to synchronize the corners of one element with those of another element. Below is the code snippet: ... When y ...

Central alignment of div with cursor

I'm experimenting with creating a unique custom cursor using a <div> that trails the movement of the mouse pointer. While the current setup works smoothly, I've noticed that when scrolling down the page, the div lags behind until the scrol ...

What is the most efficient way to extract dynamically generated JavaScript content from a webpage?

Currently, my method involves using selenium alongside PhantomJS to scrape dynamic content generated by JavaScript on a website. Although it provides me with the desired results, the process is quite slow as I have to wait for the entire page to load befor ...