What could be causing setViewValue() to fail to update values in all instances in this scenario?

index.html represents:

<!DOCTYPE html>

<html ng-app="myApp">
    <head>
        <script src="js/angular.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
    </head>
    <body>
        <div>TODO write content </div>
        <input test type="text" ng-model="name" >
        <h1>name: {{name}}</h1>
    </body>
</html>

app.js signifies:

var app = angular.module('myApp', []);

app.directive('test', function () {
    return {
        require: '?ngModel',
        link: function ($scope, $element, $attr, controller) {
            if (!controller) {
                console.log("controller of ngModel not found");
                return;
            } else {
                console.log("controller of ngModel found");
                controller.$setViewValue('qwerty');
            }
        }
    };
});

In the above example, in the link function, I am accessing the controller of the ngModel directive by utilizing the require option specified in the DDO. I then update the value of name, which reflects in the

<h1>name: {{name}}</h1>
element within index.html, but not within the
<input test type="text" ng-model="name">
element also inside index.html. Why does it update in one place but not the other?

Code @ plnkr.co

Answer №1

Found in the depths of Angular source code:

It must be emphasized that when using $setViewValue, it does not automatically trigger $render or alter the value in the control's DOM. To modify the control's DOM value through code, we need to update the underlying ngModel scope expression.

In the following sample scenario:

$parse($attr.ngModel).assign($scope, 'qwerty')

Answer №2

The function $setViewValue does not directly update the $modelValue. In order to achieve this, you must invoke the $render() function on the ngModel controller. This will transfer the $viewValue to the $modelValue, allowing the binding to work correctly on the page.

Custom Directive Implementation

app.directive('customDirective', function () {
    return {
        require: '?ngModel',
        link: function ($scope, $element, $attr, controller) {
            if (!controller) {
                console.log("ngModel controller not found");
                return;
            } else {
                console.log("ngModel controller found");
                controller.$setViewValue('qwerty');
                controller.$render(); // Update $modelValue
            }
        }
    };
});

Plunkr Link

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

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Using Javascript to extract and organize JSON arrays from various sets of checkboxes

Is there a way to automatically create an array of multiple groups of arrays like this: arr = {arr1:{index:value, index2:value2}, arr2:{index,value, index2:value2}}; The order is based on groups of checkboxes in HTML (see example below): <div class=& ...

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) { ...

Displaying information in Angular2

I'm currently facing an issue where I am unable to display certain information from my API in my view, even though the console is showing me that the necessary data is being retrieved. Below is a snippet of my Angular service: getById(id){ retu ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Having trouble with the "initSdk" property being undefined in your React Native Appsflyer integration?

I'm currently facing an issue while trying to integrate AppsFlyer into a react native application. The error I am encountering is "Cannot read property 'initSdk' of undefined" Initially, I imported the react-native-appsflyer module as shown ...

Step-by-step guide on validating a user in Joomla using AJAX and jQuery

Is there a way to authenticate a user in Joomla through an AJAX call? I want to implement an error effect if the login is incorrect and redirect the user upon successful authentication. I am specifically interested in using JQuery's .ajax API for thi ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

generate code to automatically output the content of a website

I'm in the process of creating a program that automatically navigates to a website and prints a page. Unfortunately, I'm encountering difficulties in getting it to function properly. I've attempted using the selenium chrome driver, but with ...

Executing blur event in AngularJS

Is there a way to set up an input so that when the length is equal to 5, it triggers a blur event automatically? Any tips on how to achieve this? Here is a basic concept of what I'm looking for: <input type="tel" placeholder="type here." ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Is there a way to troubleshoot the "module not found error" that keeps popping up when I attempt to execute the code following a smooth installation of sqlite3?

Initially, I successfully installed the sqlite3 module but encountered errors like "module not found". However, upon attempting to reinstall sqlite3 (npm install sqlite3), more errors surfaced that required thorough post editing. The output is as follows: ...

Modifying the values of array elements in MongoDB

I am currently attempting to modify specific elements within an array. This particular array consists of objects that have two distinct fields. The displayed output from my view is as follows: Each line in the display corresponds to the index of the objec ...

searching for a refined method to tackle this challenge

I'm relatively new to Angular and I'm interested in finding a more efficient solution for this particular task. The code below functions correctly, but I am uncertain if it is the best approach to achieve the desired outcome. HTML <div ng-a ...

What is the best way to transfer JavaScript data to HTML?

I'm having trouble displaying my JSON data in HTML. I converted the JSON data into variables and created additional variables to access specific elements within the JSON data. However, when trying to pass this data to HTML using document.getElementByI ...

AJAX is delivering a unique random hash instead of the expected text

I am in the process of developing a live notification script, and I have encountered an issue. Instead of receiving plain text from the external file, the script is returning a random hash... Here is the function responsible for fetching data from test.ph ...

Issue caused by overflowing content and resizing the display

I am facing a challenge with my website. Essentially, my webpage has the <html> set to overflow:hidden, with two horizontal navbars, a fixed vertical sidebar on the left, and a central div with the height: 90% property. Edit: The container div now ...

What is the best way to exclude a specific key when adding JSON objects to an array?

I'm facing a challenge with a JSON array of objects that contains other arrays of objects. The structure of this array is not fixed, making it difficult for me to delete specific elements like delete mainArray[0].obj.subobj[1].objToOmit; In my progra ...

Navigating through elements in the hidden shadow DOM

Can elements within the Shadow DOM be accessed using python-selenium? For example: There is an input field with type="date": <input type="date" name="bday"> I want to click on the date picker button located on the right and select a ...