Struggling with updating scope values when binding data in Angular (particularly with a slider)

Currently, I am utilizing Angular to develop a tool that can take user input from a slider tool and dynamically update an "estimate" field whenever the values are adjusted. However, I'm encountering an issue where the data is only binding in one direction; the user input is being displayed but not registering within the scope.

Below is the HTML snippet:

<h3 ng-controller="calcController" ng-model="estimate" class="floating-menu">${{estimate}}</h3>
    <form ng-controller="calcController" method="post" action="/estimate">

        <div class="container">
            <div class="vals">${{values.insurance}}</div>
            <div id="insurance-slider">
                <slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.insurance" ng-change="changeVal()" translate="currencyFormatting"></slider>
            </div>

        <div class="container">
            <div class="vals">${{values.lease}}</div>
            <div id="lease-slider">
                <slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.lease" translate="currencyFormatting"></slider>
            </div>
        </div>
     </form>

And here's the Angular code snippet:

 //creating the module 'Breeze'
   angular.module('Breeze', ['ngRoute', 'ngResource', 'ui.slider'])

   .config(function($routeProvider) {
       $routeProvider

       // route for the calculator page
           .when('/', {
           templateUrl: 'partials/calculator.html',
           controller: 'calcController'
       });
   })

    // creating the controller and injecting Angular's $scope
   .controller('calcController', function($scope, $http) {
       $scope.values = {
           // Default values
           insurance: 125,
           lease: 125,
       };

       $scope.estimate = $scope.values.insurance + $scope.values.lease
      }

       // Formatting function for currency scale bar
       $scope.currencyFormatting = function(value) {
           return value.toString() + " $";
       }
   })

I have attempted using $watch and $broadcast functions, but they don't seem to be functioning properly.

Here is how it was implemented in Angular:

   $scope.$watch("values", function(newVal, oldVal, scope) {
       scope.estimate = addVals();
    })
  $scope.changeVal = function() {
    $scope.estimate = addVals();
    console.log('hi')

   $scope.estimate = $scope.values.insurance + $scope.values.lease
  }

Any suggestions?

Answer №1

It appears that you have mistakenly included two nested instances of the ng-controller="calcController" in your HTML code. This results in two separate scopes for the controller, each with its own estimate value. Therefore, when you update the inner estimate, the outer one remains unaffected.

To resolve this issue, you should remove the second ng-controller from your <form>. If the controllers were intended to be different, you could place the estimate variable within an object like $scope.model.estimate to enable property inheritance between them. However, in this scenario, having two controllers is unnecessary.

Additionally, it is recommended that you eliminate the ng-model="estimate" from your <h3> tag, as it serves no functional purpose.

Answer №2

Just starting out by setting them equal won't be effective. Instead of including an estimate field in your view, try using this:

<div ng-controller="calcController" ng-app="Breeze">
    <h3 ng-model="estimate" class="floating-menu">${{values.insurance + values.lease }}</h3>
        <form method="post" action="/estimate">

            <div class="container">
                <div class="vals">${{values.insurance}}</div>
                <div id="insurance-slider">
                    <slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.insurance" ng-change="changeVal()" translate="currencyFormatting"></slider>
                </div>

            <div class="container">
                <div class="vals">${{values.lease}}</div>
                <div id="lease-slider">
                    <slider floor="0" ceiling="250" value="125" step="25" precision="2" ng-model="values.lease" translate="currencyFormatting"></slider>
                </div>
            </div>
           </div>
         </form>
</div>

This setup will continue to calculate as the values are adjusted.

Another issue is having two controller calls for the same controller without specifying an app. To address this, replace it with the updated div and remove the other ng-controllers.

Additionally, ensure that you have included the ui slide JavaScript file on your webpage.

Answer №3

Have you attempted binding to an object rather than a primitive type?

$scope.values.estimate = $scope.values.insurance + $scope.values.lease

For a related issue, check out this question: Angularjs: 2 way binding not working in included template

You can also view the fiddle here http://jsfiddle.net/U3pVM/9330/

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 user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

Attempting to create distinct match matchups for every team in a manner reminiscent of the Swiss system format used in the 2024/25 UEFA Champion League

I've been working on devising a tournament pairing system modeled after the updated UEFA Champion League structure. The league phase involves 36 teams, categorized into 4 different pots. Each team is scheduled to play a total of 8 matches against 2 op ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

What is the best way to trigger the code within my useEffect React hook to execute again upon refreshing the page?

I'm encountering an issue where the value of states is becoming 'undefined' after refreshing the page. Within my useEffect hook, I am generating a random number to select a question object from an array. Everything works smoothly on the ini ...

What is the process for using the scrollIntoView function on an svg element like a rectangle?

I have a graph panel with an SVG. The nodes in the SVG are listed in a separate panel. I would like for when a node is clicked in the node list, the SVG will scroll to that specific node. Each node is represented by a rectangle shape. However, I noticed th ...

maximum number of results in google custom search limit

I'm trying to retrieve the top 40 results from the Google API, but when I limit the result using the code below, it doesn't seem to work. How can I achieve getting the top 40 results with the Google API? <script> (function() { ...

What is the process for displaying the following text after deleting the particle text?

Recently diving into the world of vanilla JS and WebGL content, I managed to create a particle text effect that distorts on mouse hover. These particles are interconnected with lines, as shown in the code snippet below. const canvas = document.getElementBy ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Guide on building a Dynamic factory in AngularJS

For my project, I need to implement a dynamic factory in AngularJS with a unique name. Here is an example of what I am trying to achieve: function createDynamicFactory(modId) { return myModule.factory(modId + '-existingService', function ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

What is the best way to create a JavaScript function that can be used for multiple expandable cards in HTML and CSS?

I'm dealing with a situation where I have a list of cards, and I want to be able to expand the content individually when clicking on "more info". Can someone offer advice on how to achieve this using Javascript? Check out this CodePen for reference: ...

determine the vertical dimension of the horizontal scrollbar

I ran into an issue where I needed to determine the height of a horizontal scrollbar. This question and answer recommended using the clientHeight property to calculate the difference. Unfortunately, this method no longer works as shown here: https://jsfid ...

Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult. This is what I have so far, but I suspect the issue lies within the h variable. function formatTime(time) { var h = m = s = ...

How can I retrieve data from local storage based on a specific key value using a query?

In order to optimize the storage of data for my app, I have successfully stored a large amount in local storage. Now, I am faced with the task of fetching data in an array but only selecting key/values that are specifically chosen, rather than all or jus ...

Trigger a function in AngularJS when the datepicker values are not valid

I have successfully set min and max values for the datepicker in AngularJS Material at https://material.angularjs.org/latest/demo/datepicker. However, I also need to disable the submit button if the selected date is invalid. When attempting to use the `n ...

Setting the 'redirect_uri' for Identity Server 4 in a React JS application and directing it to a specific view using a route

After following the instructions at , I attempted to login to Identity Server from my ReactJS application. Upon successful login, http://localhost:3000/callback.html was loaded with id_token and access_token in the URL. However, I noticed that this callbac ...

Is there a way to modify the color of the horizontal line within react-native-otp-inputs in the React Native platform?

Is there a way to customize the color of the horizontal line in react-native-otp-inputs for react native? I used react-native-otp-inputs to capture user OTP input, but now I want to change the color of the default black horizontal line to white. You can re ...

What is preventing the MenuItem component from functioning as a Link in React Material-UI?

Hey there! I've been trying to implement a popover menu that changes the URL and component after clicking on an item, but unfortunately it's not working as expected. I created a setup in this sandbox: https://codesandbox.io/s/romantic-surf-40p19? ...

Express JS with multer is unable to process multiple file uploads, resulting in an empty array being

As I develop an app on Glitch with express js, the functionality requires users to upload multiple files. Here is the code snippet that I am using: var express = require('express'); var cors= require('cors'); var bodyParser= requir ...

Using a straightforward approach with v-model in vue.js on an href element instead of a select

Is there a way to utilize an href-link instead of using <select> to switch languages with vue.i18n? <a @click="$i18n.locale = 'en'">EN</a> <a @click="$i18n.locale = 'da'">DA</a> ...