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

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

Angular is unable to POST to Rails server with the content-type set as application/json

Currently, I am attempting to send a POST request with Content-Type: application/json from Angular to my Rails backend. However, an error is being displayed in the console: angular.js:12578 OPTIONS http://localhost:3000/api/student_create 404 (Not Found ...

jQuery ceases to function once AJAX content is loaded

Exploring Options for Flexible Data Display I'm currently in the process of building a webpage that allows users to choose between different layouts for loading data. This includes the option to display data in either a list format or a card interfac ...

What is the best way to invoke a function that is defined in another controller?

One thing that stands out to me about jQuery is its ability for me to write a function and access it from anywhere in my application. However, I have noticed that AngularJS operates differently, which can be frustrating at times. For instance, consider the ...

Preventing CSRF Errors when activating API endpoints in Node Express JS by ensuring that bypassing the error message with next() function is ineffective

In this middleware block, I have implemented a mechanism to render a 404 page when an invalid CSRF token is detected. /* * Middleware for rendering 404 page on invalid csrf token */ this.app.use((err: any, req: Request, res: ...

A checkbox placed within an anchor tag

Here is some code that I have: <a href class="dropdown-toggle"> <input type="checkbox" ng-model="test.checked"> <span class="fa fa-angle-down"></span> </a> When I click on the above code, I want the chec ...

Can you explain the distinction between JSON syntax and object assignment in programming?

While exploring the Twitter Client example on Knockoutjs, one may notice that some properties are included in the JSON object while others are assigned outside of it. What distinguishes these two approaches? And why can't methods such as findSavedList ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Client.on facing issue with receiving data upon initial connection

Currently, I am utilizing the net module in order to establish a connection between my client and server. Below is the code snippet: const Net = require('net'); client = Net.connect(parseInt(port), host, function() { co ...

Ajax continues to operate even if an error is detected

Hello fellow programmers! I'm currently facing an issue with form submission and validation using jQuery with 2 ajax events. The problem lies in the fact that even if the first ajax event (timeconflict.php) returns an error, the second ajax event (res ...

What is the best way to include a JavaScript variable in an HTML image src tag?

Even though I know the answer to this question is out there somewhere, I just can't seem to find it (or maybe I'm not recognizing it when I see it!). As a beginner in jquery, please be patient with me. Dilemma: I have a collection of 20 images, ...

Send the model to the route to be filled through the query parameter

I'm currently working on a task that involves creating a function to handle app routes. The goal is to pass in an object that will be filled with the fields from the request body. In my code snippet below, I encountered an error mentioning that ' ...

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

Ensure that dynamic functions are accurately typed within a proxy utilizing TypeScript

I am currently working on a unique function that utilizes a Proxy with a get trap to extract functions from multiple objects. The challenge I am facing is getting TypeScript to recognize these functions at compile time so that I can add them to my interfac ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

Troubleshooting: Next.js - Issues with encodeURIComponent function when using `/` in getStaticPaths

Reproducible site showcasing the issue: Reproducible code example: https://github.com/saadq/nextjs-encoding-issue Homepage Food page The goal is to dynamically create static pages for different food items based on their titles. This functionality works ...

Integrating webpack with kafka-node for seamless communication between front

I am in the process of embedding a JavaScript code that I wrote into an HTML file. The script requires kafka-node to function properly, similar to the example provided on this link. To achieve this, I am using webpack to bundle everything together. I am fo ...