Issues with Angular $watch causing mismatches in bindings更新(binding)

I am attempting to set default values for certain model properties by using $watches. I cannot utilize the typical two-way binding because I want the model properties to start off as empty. Although the $watches are successfully setting the properties, the associated HTML is not being updated.

<!doctype html>
<body ng-app="TestApp" ng-controller="TestCtrl">
    <div><input ng-model="form.firstname" placeholder="enter your first name"/></div>
    <div><input ng-model="form.lastname" placeholder="enter your last name"/></div>    
    <p>{{user.firstname}}</p>
    <p>{{user.lastname}}</p>
</body>

angular.module('TestApp', [])
.controller('TestCtrl', ['$scope', function($scope) {

    $scope.user = new User({
        firstname: 'Bruce',
        lastname: 'Wayne'
    });

    function User(defaults) {
        angular.extend(this, defaults);
        $scope.form = {};

        angular.forEach(this, function(value, key) {
            $scope.form[key] = '';

            $scope.$watch(function() {
                return $scope.form[key];
            }, function (val) {
                this[key] = val || defaults[key];
                console.log(val)
                console.log(defaults[key])
                console.log(this[key])
            });
        });
    }
}]);

Check out a fiddle here - my objective is for any input value to be displayed in the text, and if the value is removed, the default text appears again. The watch callback seems to be functioning correctly based on console logs. I did attempt to use $apply to update but encountered a $digest in progress error.

I am fairly new to Angular, so there's a possibility I am going about this the wrong way!

Answer №1

The issue arises when this undergoes changes in the duration of the $watch process.

    function UserData(details) {
        angular.extend(this, details);
        $scope.input = {};

        var self = this; // <-- Storing `this`.

        angular.forEach(this, function(value, key) {
            $scope.input[key] = '';

            $scope.$watch(function() {
                return $scope.input[key];
            }, function (val) {
                self[key] = val || details[key];
                console.log(val)
                console.log(details[key])
                console.log(self[key])
            });
        });

Saving this resolves the issue: http://jsfiddle.net/637yypz1/1/

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 TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

Fetching data from server using Ajax with PHP response

Need help with getting data from a PHP file on an AJAX call. Every time I make the call, it returns an error alert. Despite trying various methods, I am unable to figure out how to return an array from PHP to the AJAX call. This is what I have so far: AJ ...

Adding a row from two drop-down lists to a table and deleting it upon selection

Looking to dynamically update a table based on dropdown selection in jQuery. When a value is selected from the first dropdown list (projects), followed by a selection from the second dropdown list (employee), the selected values should be added as a new ro ...

Guide to saving an Object to a file (JSON) within the project directory using React Native for Debuggingpurposes

Feeling a bit overwhelmed trying to tackle this issue. My goal is to save data to a JSON file in real-time while debugging my application. I have a Redux store state that I want to organize neatly in a file for easier debugging, so exporting/writing the ob ...

Pattern matching for numbers within the range of 1 to 999999 with a maximum of 2 decimal places

I am attempting to implement a RegEx in JavaScript that will validate user input for amounts between 1 and 999,999. Users should also be able to enter decimal amounts with up to two digits of precision. Below are some example inputs along with their expec ...

What is the reason behind the non-exportation of actions in Redux Toolkit for ReactJS?

Currently, I am utilizing @reduxjs/toolkit along with reactjs to create a shopping cart feature. However, I am encountering an issue when attempting to export actions from Cart.js and import them into other files like cart.jsx and header.jsx. The error mes ...

What is the best way to eliminate a JSON header?

Here is the JSON data I have: { "folder": [ { "$": { "id": "471841542", "name": "Manajemen Pemasaran", "description": "", "user_id": "186868958", "shared": "1", "shared_l ...

Is it not possible to unselect the radio button?

I've been trying to implement a jQuery solution that allows radio buttons to be deselected, but I'm encountering difficulties with the prop function. Every time this code is executed, my condition ($(e.currentTarget).prop('checked')) al ...

The VueRouter is unresponsive and not functioning as expected

I have been delving into Vue. Through the npm install vue-router command, I added vue-router to my project. Subsequently, I incorporated VueRouter and defined my URL paths within the VueRouter instances located in the main.js file. I created an About compo ...

Guide on incorporating dxTreeView with AngularJS

Hello there, I am trying to utilize the dx-tree-view component. In my Home.html file, I have included the following HTML code: <div dx-tree-view="treeViewOptions"></div> And in my HomeController.js: $scope.treeViewOptions = { binding ...

Identify duplicate values in an array by comparing pairs of elements

If the array contains the data shown below: let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { na ...

Is there a way to access a local file upon clicking a button with the HTML5 File API?

I am currently working on a project where I am using jQuery along with the HTML5 File API to extract data from a local file. My goal is to retrieve text from the file only when the user clicks on a specific button, rather than automatically detecting chang ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

"Enhance User Experience with Autoplay.js for Interactive Content and Sound Effects

I'm trying to get both the animation and audio to start playing automatically when the page loads. Currently, the animation pauses when clicked, but I want it to load along with the audio playback. I attempted to use var playing=true; to enable autop ...

VueJS is unable to identify the variable enclosed within the curly braces

I recently started learning VueJS and I've hit a roadblock. My goal is to display a variable, but for some reason, instead of seeing the product name, all I get is {{product}} Here's the HTML code I'm using: <!DOCTYPE html> <html l ...

Discovering the expected parameters of a function

My function looks like this: function myFunction(params) { // TODO: something console.log(params.message) } I want to find out all the keys that the 'myFunction' function expects in the params object. Can this be done? I attempted to use ht ...

"Utilize the power of parent checkboxes in AngularJS to effortlessly toggle the selection status

Looking to toggle the selection of child check boxes depending on parent check boxes, specifically in AngularJS. Would appreciate any help with a solution. This is what I'm aiming for: https://i.sstatic.net/9M9pT.png ...

Create a MongoDB query using AJAX

My goal is to fetch the count of users using the email [email protected] through the ajax request below: function getUserCount(event) { event.preventDefault(); var queryCount = { email:'<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

How to Retrieve the Following Element in a Table Using Javascript

https://jsfiddle.net/en6jh7pa/1/ I am encountering an issue with accessing the next element, as it is returning null. When I pass "this" as the onclick parameter, I expect to be able to grab the next element using this keyword. However, it seems to be re ...