Changing various $scope object properties using ng-model

Can you help me figure out why the $scope.data variable is not updating when I input valid values in the form fields? How can I solve this issue?

Check out the code example on Codepen: http://codepen.io/uloco/pen/jboorN

HTML

<div ng-app="app" ng-controller="AppController" class="content">
    <input type="tel" ng-model="form.phone" placeholder="phone" />
    <input type="email" ng-model="form.email" placeholder="email" />
    <p>{{form}}</p>
    <p>{{data}}</p>
</div>

JS

angular
.module('app', [])
.controller('AppController', function($scope) {
    $scope.form = {};
    $scope.data = {
        foo: 'bar',
        phone: $scope.form.phone,
        email: $scope.form.email
    }
});

Answer №1

What is the reason for the lack of updates in the $scope.data variable?

The issue lies in the absence of a connection between $scope.data and $scope.form. These two are separate objects with their own independent properties, so any changes made to the $scope.form will not be reflected in the $scope.data.

If you wish to keep these as distinct objects, you will need to manually synchronize them using either $scope.$watch on the $scope.form:

$scope.$watch('form', function(obj) {
    $scope.data.phone = obj.phone;
    $scope.data.email = obj.email;
}, true);

Check out the demonstration here: http://codepen.io/anon/pen/PPvvBr?editors=101

Alternatively, you can use ngChange directives:

<input type="tel" ng-model="form.phone" placeholder="phone" ng-change="sync()" />
<input type="email" ng-model="form.email" placeholder="email" ng-change="sync()" />

And then define the synchronization function like this:

$scope.sync = function() {
    $scope.data.phone = $scope.form.phone;
    $scope.data.email = $scope.form.email;
};

See the demo using ngChange here: http://codepen.io/anon/pen/bVyyQN?editors=101

In this scenario, the ngChange solution is recommended. However, if there are more than two fields involved, using $watch might be simpler.

Answer №2

If you want to dynamically update phone and email fields, you can use ng-change directive in AngularJS:

 $scope.updateFields = function(data){
        $scope.data.phone = data.phone;
        $scope.data.email = data.email;
    };

Then in your HTML:

<input type="tel" ng-model="form.phone" placeholder="phone" ng-change="updateFields(form);"/>
<input type="email" ng-model="form.email" placeholder="email" ng-change="updateFields(form);"/>

Answer №3

Upon setting up the controller, both $scope.form.phone and $scope.form.email are initially undefined. However, even if $scope.form undergoes changes, $scope.data remains unaware since it simply contains "undefined".

To access the data, you can create a function like the following:

$scope.retrieveData = function () {
    return {
        name: 'John Doe',
        phoneNumber: $scope.form.phone,
        emailAddress: $scope.form.email
    };
};

This ensures that the object is freshly initialized whenever required.

Answer №4

The content within your $scope.data variable remains the same even when the phone or email fields are changed.

Consider implementing the $watchGroup function to monitor changes in both phone and email fields at once.

$scope.$watchGroup(['form.phone', 'form.email'], function(newValues, oldValues, scope) {
  scope.data = {
        foo: 'bar',
        phone: scope.form.phone,
        email: scope.form.email
 }
});

Answer №5

If you want to incorporate HTML

<div ng-app="app" ng-controller="AppController" class="content">
    <input type="tel" ng-model="form.phone" placeholder="phone" />
    <input type="email" ng-model="form.email" placeholder="email" />
    <p>form: {{form}}</p>
    <p>data: {{data()}}</p>
</div>

For JavaScript:

angular
    .module('app', [])
    .controller('AppController', function($scope) {
        $scope.form = {};
        $scope.data = function() {
            return {
                foo: 'bar',
                phone: $scope.form.phone,
                email: $scope.form.email
            };
        }
    });

Check out the updated codepen here: http://codepen.io/anon/pen/Xmwwye

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 power of Ionic 2 combined with the Web Audio API

I am currently developing an Ionic 2 application that requires access to the user's microphone. When working on a web platform, I would typically use the following code snippet to obtain microphone access. navigator.getUserMedia = (navigator['ge ...

Can someone guide me on running a JavaScript code in Python with the help of Selenium?

My attempt to extract information using Selenium involved the following code: from selenium import webdriver # $ pip install selenium from selenium.webdriver.chrome.options import Options path = 'C:/Users/Жираслан/Downloads/chromedriver_win3 ...

AngularJS - Enhancing $httpProvider Interceptor to process and transform response data

Is it possible to implement an interceptor for handling error status codes in AngularJS? For instance, if I try to load a template using $route and encounter a 403 error due to lack of permission, can I display custom HTML data instead of the requested tem ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...

Creating a JSON array using looping technique

I am attempting to construct a JSON array using a loop where the input className and value will serve as the JSON obj and key. However, I am facing difficulties in creating one and cannot seem to locate any resources on how to do so. Below is an example sn ...

After selecting "ok" on the JavaScript alert dialog, the webpage will automatically refresh, causing all information entered into the textboxes to be erased

<?php include "dbconfig.php"; session_start(); ?> <!DOCTYPE html> <html> <head> <title>Log in</title> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="bo ...

Reveal the class to the global scope in TypeScript

ClassExample.ts: export class ClassExample{ constructor(){} } index.html: <script src="ClassExample.js"></<script> // compiled to es5 <script> var classExample = new ClassExample(); //ClassExample is not defined < ...

Extracting timestamped text data from a simulated chat interface

I am looking to gather chat data from Twitch clips. These are saved moments from livestreams where viewer reactions are captured. Take a look at this example clip: While I can scrape all the data by watching the video and utilizing query selectors, my goa ...

Obtain the orientation of the threejs scene and camera to establish the initial perspective

Currently, I am facing challenges in configuring the default camera position and orientation for my THREE.JS demo. I aim to manually adjust the view/scene/camera through trackball interaction and then find a way to set the correct camera settings to establ ...

What is the best way to add external javascript files to bookmarklets?

I have been developing a CDN for a collection of scripts that I created for my job. Previously, I had to distribute these scripts individually and each user would have to download and install them on their own computer. Now, I am transitioning them to an A ...

Route.post() is in need of a callback function, however, it was provided with an [object String

I've been working on developing my own vocabulary app by following and modifying the MDN node/express tutorial. While the MDN tutorial runs smoothly, I'm encountering issues with my version. Below are the errors I'm facing: Error: Route.p ...

Understanding the inArray Method in JQuery

I'm working on creating a validation method to make sure that users don't input duplicate names. I thought using the inArray method would help me determine if the value is already in an array: if(jQuery.inArray(newName, nameArray) >= 0) { ...

Avoid tampering with forms in PHP, JavaScript, and JQuery to maintain security measures for PayPal transactions

Users have the option to purchase credits on my form using PayPal or bank transfer as payment methods. If a user chooses "PayPal," the form data will be sent to PayPal using JQuery/JS: $(':radio').change(function () { var $this = $(this).val(); ...

What is the best way to sum up all the values per month from a JSON file in React and showcase it as a single month using ChartJs?

Apologies if I didn't explain my question clearly enough. As a junior developer, sometimes it's challenging to ask the right questions, and I'm sure we've all been there, right? The data in my JSON file is structured like this: [ { &qu ...

Locate components within JQLite

I need assistance accessing the JQLite element of a div with the class "dialog" in an angular directive. Unfortunately, I can't use element.find('div') because there is another div in the template. After coming across a similar question (An ...

Utilize Services without creating circular interdependencies

My app utilizes a GlobalDataService (GDS) to store all data globally. GlobalDataService (GDS) angular .module('app.core') .service('GlobalDataService', GlobalDataService); GlobalDataService.$inject = ['$http&a ...

Is there a different option than using 100vh for fixing positioned elements?

I'm working on a flex container with a nested div for top navigation. I want the top-nav to expand and occupy the full height of the viewport when it expands. Setting a height of 100vh seems like the obvious choice, but I'm looking for a more wid ...

The use of Angular's ng-repeat within a <tr> element disrupts the functionality of

Currently, I am working with version 1.4.8 of Angular. My code involves an array of strings which I am using to iterate over a table using ng-repeat. Within this iteration, there are three cascading dropdowns. However, I have encountered an issue where the ...

Adjust the color of the glyphicon icon within a date and time picker dropdown component

I decided to implement the bootstrap datetimepicker using this gem and utilized the following HTML code: <div id="custom-dates" style=" clear:both;"> <div class="container"> <div class="row"> <div class='col-md-3 col-xs-3' ...

Emphasize any word starting with an @ symbol to highlight its importance

My goal is to enhance the appearance of words that begin with an "@" symbol by making them bold. For example, transforming the sentence: '@xyzharris has a cat @zynPeter' into: '@xyzHarris has a cat @zynPeter' ...