How to reference a variable using a string in AngularJS

I am trying to update the state of a variable by accessing it.

function changeValue(source, target, unit) {
    $scope[target] = process($scope[source] + unit + ".").toKilograms();        
}); 

This function is triggered every time something is inputted into a field (when tabbing out). However, the issue is that the value in the input field bound to $scope[targetVariable] does not update unless you click inside the input box.

Note: If I use the variable in a standard way, it works without any problems.

Answer №1

To ensure your variable is updated correctly, make sure to include it inside $scope.$apply:

function updateValue(inputVariable, outputVariable, inputUnit) {
    $scope.$apply(function() {
          $scope[outputVariable] = convert($scope[inputVariable] + inputUnit + ".").toGrams();      
    });  
}); 

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 jQuery .on event function is not compatible with a dynamic selector

I am facing a challenge in creating an onClick functionality for a dynamically loaded element with an ID stored in a variable called $element. The ID is in string format and I am trying to pass it to the event handler using the .on method like this: ... . ...

In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line? if (!user) { const error = new Error('Invalid user.') error.data = someObject error.code = 401 throw error } Here's an example (with data and code properties populated) if (!user) th ...

Tips for building an interactive jQuery data table using JSON information and AJAX requests

Currently, I am attempting to develop a dynamic data table using jQuery and JSON. My objective is to extract the keys from the JSON data and utilize them as headers in the table, while the values within those keys will be displayed as rows. Here's th ...

When utilizing getServerSideProps, the data is provided without triggering a re-render

Although my approach may not align with SSR, my goal is to render all products when a user visits /products. This works perfectly using a simple products.map(...). I also have a category filter set up where clicking on a checkbox routes to /products?catego ...

Creating an extensive amount of HTML content through the use of JSON

When I request data from my API, it returns JSON objects which then populate numerous divs with content. However, I find myself continuously using concatenation to insert object properties. Is there a more efficient method for achieving this? $.each(JSO ...

Error retrieving the series value for chart-click on the angular stacked bar graph

<canvas class="chart chart-bar" chart-data="data" chart-labels="labels" chart-options="options" chart-series="series" chart-click="onclick"></canvas> 'use strict'; var app = angular.module('examples', [&a ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Creating transclusion templates in a compiled format

<div overlay config="overlayConfig"> <div class="dismiss-buttons"> <button class="btn btn-default" ng-click="subscriptions()">Save</button> </div> </div> app.directive("Overlay", ["$timeout", "$compile ...

How can you switch between CSS styles using JQuery?

Is there a way to change CSS properties every time I click using jQuery? I couldn't find any information on this specific topic. Can someone guide me on how to achieve this with jQuery? I want the background color to change each time it is clicked. W ...

Is there a way to determine the number of clicks on something?

I'm attempting to track the number of times a click event occurs. What is the best method to achieve this? There are two elements present on the page and I need to monitor clicks on both of them. The pseudo-code I have in mind looks something like ...

Is it possible to include a class in a placeholder?

Adjusting some modifications in ui-grid.js to fit my needs. Experimented with incorporating unicode in the placeholder, and it is functioning smoothly. However, I am in search of a generic (black and white) search icon instead of the default blue framed on ...

How can Angular be used to dynamically show or hide an element based on its height?

Is there a way in Angular to display a "Read More" link once the height of a paragraph reaches 200px? I'm looking for an elegant solution. Here are my elements: <section class="mynotes" ng-if="MyController.mynotes"> <p ng-bind="MyController ...

Tips for smoothly transitioning elements to a visible state with a Fadein effect

I have been using a code snippet I found to fade in elements with the class "hideme" as I scroll to them. However, the elements only fade in when they are fully visible. Is there a way to modify the code so that they fade in as soon as they appear in the b ...

Uploading files from AngularJS with ng-flow to Node/Express can be achieved by utilizing empty request bodies

Currently, I am utilizing ng-flow for the purpose of uploading an image. I am facing a challenge where I need to configure my upload to have a content type of application/json. I found some insights on this matter in the following link: Node (Express) req ...

Calling JavascriptInterface in an H5 environment is not permitted

Utilizing the power of vue, I created an immersive h5 page within the application framework. The seamless connection between the page and the app relies on the use of window.JSInterface for communication. My current challenge lies in invoking the JSInterfa ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

The post request with Postman is functional, however the AJAX post request is not working. I have thoroughly reviewed the client-side JavaScript

I encountered a problem with an endpoint designed to create an item in my application. Sending a POST request through Postman works perfectly fine, as I am using Node.js and Express for the backend: router.post("/", jwtAuth, (req, res) => { console.lo ...

Modifying the HTML attribute value (of input) does not impact the value property

After inputting a single tag, I ran the following code in my Chrome console: https://i.stack.imgur.com/ySErA.jpg The result was unexpected for me. According to what I have read in a book, when I change an HTML attribute, the corresponding property should ...

How to automatically reset a form after submission in React using Ant Design?

When using the antd template for form design, I encountered an issue where form input values were not getting cleared after submission. I attempted to use this.props.form.resetFields(), but it resulted in the following error: Unhandled Rejection (TypeErro ...

Animating background images using a single data attribute

I'm attempting to create a smooth animation between different background images stored in a single data attribute. The goal is for each image to load sequentially, with the first one appearing immediately and the rest following after a 5-second delay. ...