What is the relationship between Angular's $watch function and a slider component?

Hello everyone! I am a beginner in the world of Web Development and I've run into an issue. Luckily, I was able to create a fiddle showcasing my problem for better understanding.

The challenge at hand involves two sliders: one for a value and another for weight. These sliders are repeated n times using the ng-repeat function - in the fiddle, I have demonstrated this setup with just two repetitions.

What I aim to achieve is calculating an index based on the following formula:

Value1*Weight1 + Value2*Weight2

The index calculation utilizes the reduce function. However, my predicament lies in the fact that the index value does not update when the slider values change. While I believe $watch might be the solution, I am unsure how to implement it.

If anyone could provide some guidance or assistance, I would greatly appreciate it.

You can access the js fiddle through the link below:

https://jsfiddle.net/dkyun/dfx0grdr/

Answer №1

To enhance your code, consider implementing the following approach:

  $scope.index = 0;

  $scope.calcIndex = function(){
    return $scope.alerts.reduce(function(prev, next) {
      return prev + (next.value*next.weight);  
    }, 0);
  };

  $scope.$watch(function(){
    return $scope.calcIndex();
  }, function(newValue){
    $scope.index = newValue;
  });

VIEW THE LIVE DEMO

Answer №2

To keep your scope's index property updated with changes in alerts, it is recommended to implement a deep watch on alerts:

$scope.$watch('alerts', function() {
    var index = $scope.alerts.reduce(function(prev, next) {
      return prev + (next.value*next.weight);  
    }, 0);

    $scope.index = index;
    console.log(index);
}, true);

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

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

Tips for eliminating duplicate values from an array of objects in JavaScript

I am working with an array of objects where my goal is to remove duplicate values from the values array. I would like the final result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', v ...

How to use Javascript 'if statement' to check for a numerical value in a form field?

I am currently using some JavaScript within a Mongoose Schema to automatically increment a value if no number is manually entered in the form field. // before validation starts, the number of Items is counted..afterwards, the position is set ItemSche ...

What is the best way to extract every nth digit from a number using a given reference point?

The subject of the title may cause confusion, so let me clarify my goal. With values of n = 51 and m = 24, I aim to achieve this result: [ {start:0, end:24}, {start:24, end:48}, {start:48, end:51} ] Currently, I have made progress on this ...

Transferring data between functional components in ReactJS and dealing with the output of [object Object] or undefined

I'm struggling with passing a prop in functional components that are both located in the same .js file. I previously attempted to seek help for this issue, but unfortunately, it wasn't productive. My goal is to extract the member_id from the GET ...

Error: Typescript is not properly recognizing 'jasmine' methods

I'm facing an issue where Jasmin methods (such as createSpyOjb) are not being recognized even after adding a definition file. Could anyone shed some light on why this might be happening? ...

The issue arises when attempting to apply a filter to an array, as the variable returns as

After successfully using local state, I encountered an issue with Redux where the component returned undefined. How can I effectively compare two arrays and filter out users who are already in the current users array? import { FETCH_USERS_TO_ADD } from & ...

Clearing hoverIntent using jQuery

In my scenario, I have three items identified as X, Y, and Z. The functionality of hovering is controlled by the hoverIntent. When I hover on item X, a tooltip is displayed using the following code: jQuery('.tooltiper').hoverIntent({ ove ...

breezejs: Non-scalar relationship properties cannot be modified (Many-to-many constraint)

Utilizing AngularJS for data-binding has been smooth sailing so far, except for one hiccup I encountered while using a multi-select control. Instead of simply adding or removing an element from the model, it seems to replace it with a new array. This led t ...

Challenges surrounding jQuery's .before

Currently, I am in the process of creating a simple carousel consisting of 4 divs. The carousel is utilizing 2 jQuery functions to position a div at either the first or last slot. The transitions being used are only alpha transitions as there is no need fo ...

Creating a program to ascertain whether two integers inputted by a user are odd numbers

I need assistance in creating a function that can ascertain whether two numbers input by the user are odd and then return a boolean value that is true only if both numbers are odd. I'm already familiar with creating a function to check for even number ...

Uncovering the key based on the value in MongoDB

I'm currently working with Node.js using the express framework and Mongoose for MongoDB, and I've got a query regarding efficient data retrieval. Imagine having a mongo document structured like this: test : {a:1, b:2, c:2, d:1}; While it' ...

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

Angular Jasmine encountered an unexpected request error while using $location and $httpBackend

My goal is to unit test the functionality of $urlRouterProvider.otherwise in order to display the URL as whatever the user has entered. However, whenever I attempt to use $location in my unit test, I encounter the following error: path default rerouting s ...

Steps for transferring data from a POST response to the client in NodeJS/ExpressJS

I am currently in the process of setting up an EasyPost API and I need to save some data that is included in a response from a POST route. My goal is to send this data directly to the client for storage, but I am struggling to determine where or how to do ...

Tips for preventing click events from interfering with execution in React

On my screen, there is a specific image I am looking to prevent all actions while a process is running. When I trigger the Execute button, it initiates an API call that can take 4-5 minutes to complete. During this time, I need to restrict user interacti ...

Having trouble with input event listeners in JavaScript?

I've been attempting to trigger the keyup event using EventListener for an input tag, but it doesn't seem to be working and I'm unsure why. Here is the code I have: document.getElementById("ajax").addEventListener("keyup", function() { ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Shifting a div element around the webpage and letting it fall into place if it intersects with another div using plain JavaScript

Check out this jsFiddle link. Upon opening it, you will encounter a moveable div. However, I am looking to enhance this functionality by allowing the div to disappear if moved to the 'trash' area. Essentially, when you place the moveable div in t ...

Confirmation message is displayed upon clicking to delete a row in the editable Gridview, prompting the user to

One issue I am facing is with a Delete button in an editable Gridview on my ASP.NET application. When the delete button is clicked, it triggers a function that displays a confirmation popup asking the user for feedback on whether they want to proceed with ...