Data binding in one direction with 2 input fields

In the registration form, there are fields for firstname, lastname, and displayname. When the firstname is updated, I want that change to be reflected in the displayname field if it's currently empty.

I've set the update to happen on blur, and after inspecting the element directly for displayname, I noticed the value attribute is being set to the firstname value. However, this change doesn't seem to appear on screen or in the model. The issue seems to be because the field is referencing user.displayname (which starts off as empty).

<div ng-app="myApp">
    <form ng-controller="RegisterCtrl">
        <input type="text" ng-model="user.firstname" placeholder="Firstname"  ng-model-options="{updateOn: 'blur'}"/>
        <input type="text" ng-model="user.lastname" placeholder="Lastname" />
        <input type="text" ng-model="user.displayname" placeholder="Display"  value="{{user.firstname}}"/>
    </form>
</div>

<script>
    var myApp = angular.module("myApp", []);

    myApp.controller("RegisterCtrl", ["$scope" ,function ($scope) {
        $scope.user = {};
    }]);
</script>

JSFiddle: http://jsfiddle.net/mbqs7xcj/

Any suggestions or insights on what might be causing this? Thank you.

EDIT

One workaround I came up with was using $watch to monitor changes in the firstname field and updating the displayname accordingly only if it's empty. However, I believe there must be a better and more efficient solution to address this issue.

<script>
var myApp = angular.module("myApp", []);

myApp.controller("RegisterCtrl", ["$scope", function ($scope) {
    $scope.user = {
        firstname: "",
        lastname: "",
        displayname: "",
        email: "",
        password: ""
    };

    // Set the firstname as the display name if it's empty
    $scope.$watch("user.firstname", function () {
        if ($scope.user.displayname.length === 0) {
            $scope.user.displayname = $scope.user.firstname;
        }
    });
}]);
</script>

http://jsfiddle.net/mbqs7xcj/7/

Answer №1

delete the ng-model directive from the input display

<input type="text"  placeholder="Display"  value="{{user.firstname}}"/>

check out the Fiddle

if you are using Angular's ng-model, make sure the model name has a valid value, otherwise the textbox won't update because there is no value for user.displayname.

Answer №2

One potential solution is to trigger and monitor a mouse event on the initial input field.

<input type="text" ng-model="user.firstname" ng-mouseleave="checkDisplayName($event)" />

http://jsfiddle.net/darul75/mbqs7xcj/9/

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

Exploring the range of a directive: What you need to know

Here is a link to my code snippet on Plunker that illustrates the issue: http://plnkr.co/edit/bNha1xOrnhnyhvXtXSnX?p=preview angular.module('docsTransclusionExample', []) .controller('Controller', ['$scope', function($scope) ...

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...

The impact of a variable in a function with XMLHttpRequest

How does the XMLHttpReqeust variable impact the functionality of the following code snippets? function getHTTPObject() { if (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () { try { return new Ac ...

The shadow cast by the point light in Three.js seems to be misplaced

Take a look at this JS fiddle to view my code. I'm encountering an issue where there is a gap between the object and its shadow. Interestingly, this gap does not occur with spot lights. Any suggestions on how I can resolve this? Highlighted code snip ...

Is there a way to trigger the mouseover event on every element currently under the cursor?

In my web application, I have a feature where a dot is created every time you click. However, when hovering over a stack of dots, only the top dot triggers the mouseover or mouseenter event. How can I ensure that the events fire for every dot under the cur ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

A guide on updating various states using React Hooks

Creating a background component with the use of Vanta in NextJS, here's the code snippet: import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import FOG from "vanta/dist/vanta.fog.min"; im ...

Tips for incorporating broadcasting into my Angular application?

console.log('js'); var myApp = angular.module('myApp', ["ngRoute"]); myApp.config(function($routeProvider) { $routeProvider.when('/', { templateUrlnp: 'views/partials/logIn.html', controller: 'LoginC ...

How can I loop the keyframe animation across various elements of an SVG file simultaneously?

After creating an animation using CSS and SVG, I am experiencing different parts of it animating in and out. My goal is to have the animation start from the top once it's finished. There are multiple keyframes involved since I'm animating variou ...

Trouble with the x-cloak attribute in alpine.js

Experience with TailwindCSS and AlpineJS in my current project has brought to my attention a slight issue with the header dropdowns flashing open momentarily when the login page loads. I attempted to use x-cloak to address this, but encountered some diffic ...

The error message "The script 'physi.js' cannot be accessed due to its origin being 'null'" is encountered

Recently, I attempted to experiment with the physi.js library. I diligently followed all the provided instructions: https://github.com/chandlerprall/Physijs/wiki/Basic-Setup To my dismay, an error message popped up: Uncaught SecurityError: Failed to con ...

What is causing my component to render the count value twice?

This is my main layout component: function MainPage() { return( <div> <MLayout children={<MNavbar custOrFalse={false} />} /> </div> ); } export default MainPage; Here is the child navbar compone ...

The Angular JavaScript code displays the message variable in the web browser

When using Angular JavaScript, the browser displays {{message}}. I have tried multiple approaches but it still doesn't work as expected. var myApp=angular.module("mod",[]); myApp.controller("con", function($scope){ $scope.message = "hhhhhhhh"; }); ...

Tips on updating time zone settings in a browser using React JS or JavaScript

I am currently facing a requirement where I need to adjust the application's time based on an environment variable. The entire application should operate using the timezone specified in the configuration file. For instance, if the designated timezone ...

Is it possible for you to provide both a status code and an HTML webpage?

I've been working with the express framework in node, but I'm unsure if what I'm doing is best practice. I want to send a specific status code such as res.status(200).send("Success"); when the form input matches the server, and another statu ...

Issue with combining overflow-x, Firefox, and JavaScript

In Firefox, an issue arises that does not occur in other browsers. To see the problem in action, please visit this example page: -removed- Try selecting a page other than the home page. The window will scroll to your selection. You can then scroll down u ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...