Monitor and adjust variables simultaneously using AngularJS

My goal is to dynamically calculate and display values based on two other variables in real time.

I've successfully managed to track one variable, but not both simultaneously.

$scope.color_slider_bar = {
    value:0,
    minValue: 0,
    maxValue: 100,
    options: {
        ceil: 100,
        floor: 0,
        translate: function (value) {
            return value + ' CHF';
        },
        showSelectionBar: true,
        getSelectionBarColor: function(value) {
          if (value >= 0)
            return '#00E3C6';
        },
        onEnd: function () {
            $scope.priceselected = $scope.color_slider_bar.value;
            console.log($scope.priceselected);
        }
    }
};

$scope.selectOffer = function(offer){
    $scope.companydata.selectedoffer.push(offer)

    $scope.$watch(['$scope.companydata.selectedoffer', '$scope.priceselected'], function() {
        if ($scope.companydata.selectedoffer.length == 1){
            $scope.finalprice = $scope.priceselected;
            console.log($scope.finalprice);
        }
        else if ($scope.companydata.selectedoffer.length == 2){
            $scope.finalprice = $scope.priceselected / 2;
            console.log($scope.finalprice);
        }
        else if ($scope.companydata.selectedoffer.length == 3){
            $scope.finalprice = $scope.priceselected / 3;
            console.log($scope.finalprice);
        }
    });
}

In the first function (slider), I establish $scope.priceselected. The second function adds elements to $scope.companydata.selectedoffer.

Below is the corresponding HTML:

<div class="col-xs-12" ng-repeat="offer in offers" ng-class="{'selected': offer.chosen}">
  <div class="worditem" ng-show="!offer.chosen" ng-click="selectOffer(offer)">
     <div class="table">
        <div class="table-cell numbers">
          <div class="title">{{offer.name}}</div>
          <div class="info">{{offer.info}} / {{offer.views}}</div>
          <a data-toggle="modal" data-target="#{{offer.price}}">+ INFO</a>
        </div>  
      </div>    
  </div>

  <div class="worditem" ng-show="offer.chosen" ng-click="unselectOffer(offer)">
    <div class="overlay-price">{{finalprice | number : 0}}<br>CHF</div>
    <div class="table">
     <div class="table-cell numbers">
        <div class="title">{{offer.name}}</div>
        <div class="info">{{offer.info}} / {{offer.views}}</div>
        <a data-toggle="modal" data-target="#{{offer.price}}">+ INFO</a>
      </div>
      <div class="overlay" ng-show="offer.chosen">
      </div>
     </div>   
  </div>

</div>

The calculation of $scope.finalprice now updates when elements are added or removed from $scope.companydata.selectedoffer, but not when adjusting the slider (which changes the value of $scope.priceselected)

What am I overlooking?

Answer №1

Using angular two-way binding eliminates the need for the watch function to assign new values.

If your color_slider_bar.onEnd() is functioning correctly, you can safely remove the watch function as the new values will be automatically binded, making your code operational.

$scope.selectOffer = function(offer){
    $scope.companydata.selectedoffer.push(offer)

    //$scope.$watch(['$scope.companydata.selectedoffer', '$scope.priceselected'], function() {
        if ($scope.companydata.selectedoffer.length == 1){
            $scope.finalprice = $scope.priceselected;
            console.log($scope.finalprice);
        }
        else if ($scope.companydata.selectedoffer.length == 2){
            $scope.finalprice = $scope.priceselected / 2;
            console.log($scope.finalprice);
        }
        else if ($scope.companydata.selectedoffer.length == 3){
            $scope.finalprice = $scope.priceselected / 3;
            console.log($scope.finalprice);
        }
    //});
}

I hope this explanation proves beneficial to you.

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

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...

Developing a placeholder directive with AngularJS

Are you looking to create a unique element in AngularJS to facilitate nested ng-repeats? Take a look at the example below: data.test = [{h:1, d:[11,12]}, {h:2, d:[21,22]}]; ---------------------- <custom ng-repeat="a in data.test"> <h3>{{a ...

How can I transfer data from an API response containing an array of objects to a new array in a Vue.js

How come I am getting NaN instead of "qwe" and "qweqweqwe" when trying to push the first 6 elements from an array of objects to a new array? Imagine the array of objects retrieved from the API is structured like this: 0: {id: 340, name: "qwe", lastname: ...

Leverage socket.io in various routes within a node.js application

In my Node.js application, I have various routes defined in the router.js file. Now, I want to implement socket.io in every route to enable real-time communication between my Node.js and React.js applications. However, the structure of my Node.js applicati ...

The Angular model finally refreshes its values after a console.log() is executed

UPDATE After further investigation, I discovered that the issue was not related to Angular itself, but rather a mistake in the update function within the node server controller. I have provided the fix below for reference, and decided to keep this questio ...

Ways to display numerous cards on individual Carousel slides using react-bootstrap

Currently, I am utilizing react-bootstrap to handle my data from an API, which is stored in an array called recipes. My challenge lies in attempting to display 3 items on each slide of a Carousel using react-bootstrap. As of now, each item is appearing on ...

Every time I invoke a module, non-global variables are utilized

Within a module.exports file, I am facing an issue where the variables are shared among different instances of the module. Instead, I want each call to the module to have its own set of values for cycle number, original data, new product, etc., similar to ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

Tips for effectively utilizing "Session" in jQuery

Are there any comparable features in jQuery to Session["Param"] in C#? How can I implement it? I've looked up "sessionStorage" in jQuery, but I'm having trouble grasping it. ...

Unable to assign values to object variables in JavaScript

I'm currently working on a project in AngularJS that involves reading data from files. The goal is to assign the content to a variable within an object if the file is read successfully, otherwise, assign "NA" to the same variable. function customer($ ...

The process of rendering children elements in React

I have a question about managing children components in React. While there are resources available explaining this concept, I believe a more detailed explanation would be helpful. Let's consider the structure of my React component tree, which looks l ...

Issues with clicking in JS eventListener

I'm in need of some assistance with a small header issue in my project. I've included all the necessary header files so that you can run it in a snippet and see what's going on. The problem lies within my JS file. When running the file, you ...

Maintain authentication state in React using express-session

Struggling to maintain API login session in my React e-commerce app. Initially logged in successfully, but facing a challenge upon page refresh as the state resets and I appear as not logged in on the client-side. However, attempting to log in again trigge ...

Moving objects with Three.JS

Seems like I might just be overlooking a simple solution here. I have a setup with a spotlight pointing backward from the camera towards a plane geometry, as well as some randomly scattered boxes. My goal is to create a basic top-down demo. I move the came ...

The Mean stack application is throwing an error message: "user.comparePassword is not

This section contains my user models in the file named "user.js". var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); let emailLengthChecker = (email) => { if (!email) { return false; } else { if (emai ...

Avoiding cheating in a JavaScript game

I am in the process of creating a JavaScript/JQuery game that resembles a classic brick breaker. The game includes features such as scoring, levels, and more. I have plans to add a leaderboard where users can submit their final scores. However, my concer ...

Implementing conditional rendering using custom division return functions with onClick attribute on a submit button in React: A step-by-step guide

import React from "react"; class Input extends React.Component { constructor() { super(); this.state = { phone: "", weight: "", height: "", gender: "", smoke: "", lazy: "", bmi: "", pain: "", ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

angular.copy reflects modifications in assigned variables

let originalCart = angular.copy($rootScope.cart); let cartCopy = angular.copy(originalCart); At some point in my code, I am making changes to the $rootScope.cart variable. However, these changes are also affecting the cartCopy variable, which I would li ...

Upon attempting to retrieve a package version, NPM responds with an error stating "bash command not found."

I recently set up my project with a package.json file that includes the nodemon package among others. When I run #npm list --depth 0 in the terminal, this is what I see: ├─┬ [email protected] However, when I try to check the version of nodemo ...