What is the correct way to effectively utilize ng-bind (one-way binding) with form inputs?

section, I have observed that changing the value of input2 manually and then altering the values of input1 results in input 2 not being updated any further. This raises the question: does this mean that the one-way binding in the form inputs will be disrupted if the user enters something into it?
    
    <div ng-controller="myCtrl">
        1: <input name="input1"  ng-model="topValue"/>
        2: <input name="input2"  value="{{topValue}}"/>
        topValue: <span>{{topValue}}</span>
    </div>

Answer №1

ngValue does not work with input[text]

According to the ngValue documentation:

The ngValue directive binds the given expression to the value of input[select] or input[radio], setting the ngModel of the element to the bound value when selected.


While debugging ngValue with input[text]:

  • Check in the ngValueDirective (input.js)
  • The $watch callback was triggered when input1 changed.
  • attr.$set('value',value); only changes the inner-editor (see below)
  • Replacing it with elm[0].value = value || ""; resolves the issue:


var ngValueDirective = function() {
  return {
    priority: 100,
    compile: function(tpl, tplAttr) {
      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
        return function ngValueConstantLink(scope, elm, attr) {
          attr.$set('value', scope.$eval(attr.ngValue));
        };
      } else {
        return function ngValueLink(scope, elm, attr) {
          scope.$watch(attr.ngValue, function valueWatchAction(value) {
            //attr.$set('value', value);
            elm[0].value = value || "";
          });
        };
      }
    }
  };
};

When interpolating with value (or any other attribute):

  • Angular creates $observe in the addAttrInterpolateDirective function (compile.js)
  • When the $observe callback is triggered, it uses attr.$set(name, newValue), leading to the same issue;

Conclusion -

Answer №2

Absolutely. If a user modifies the content of input2, the value of input2 will no longer be recognized as an AngularJS expression, causing any alterations to topValue to go unnoticed.

Answer №3

Summary: The binding is functional.

Expanded Explanation:

When dealing with elements, it's important to distinguish between attributes and properties. This difference is especially noticeable with attributes of an input element.

The value attribute represents the initial or default value of the element. However, once you start typing in the input field, the value attribute becomes irrelevant.

Therefore, when using an angular expression like value="{{topValue}}", the attribute's value will update whenever the expression {{topValue}} changes. Nevertheless, once the content of the input field is altered – whether manually or programmatically by modifying the value property of the input element – this attribute value becomes inconsequential.

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 display HTML and JavaScript content using Express?

Currently, I am working on a simple express app which comprises of two routes. One route is responsible for rendering html, while the other route is supposed to render a JavaScript file. To keep things organized, I plan to store the html files in a ./views ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

Troubleshooting a Form Validation Issue with React's useState Hook

I am currently working on form validation for a project. The form includes two essential elements: a textbox for messages and a textbox for recipients. These elements are controlled by state.message (a string) and state.recipients (an array). The state var ...

"Utilizing the v-autocomplete component with on-select and on-remove events in Vuet

Are there any on-select or on-remove properties available in v-autocomplete from Vuetify? I need to manually handle these events. I have tried using @change, but it does not inform me whether an option has been added or removed. <v-autocomplete : ...

Disable the functionality of the next and previous buttons for the Bootstrap carousel when clicking on the outer

Here is the code for the carousel: The next/prev button functions under its respective div, how can I stop it? When I click on the div below the carousel, the carousel continues to move as usual. Below the carousel div, there is another one with a tabbi ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

NodeJS application does not acknowledge the term "Require"

I have completed the steps outlined on http://expressjs.com/en/starter/installing.html to set up my express NodeJS application. Following the installation, we navigated to the "myapp" directory and installed the "aws-iot-device-sdk" from https://github.com ...

Help needed with parsing nested JSON using the $.each function

Here is a JSON response sample that needs to be parsed in a more generic manner, rather than using transactionList.transaction[0]. "rateType": interestonly, "relationshipId": consumer, "sourceCode": null, "subType": null, "transactionList": { "transac ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expectin ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

The DOM does not contain unscrolled rows in the DataTable's infinite scrolling feature

Every time I create a dataTable with infinite scrolling, I use the following code: $('#table1').dataTable({ 'aaData' : dataArr, 'aoColumns': columnArr, 'bScrollInfinite': true, 'bColumnCollapse& ...

Enhance User Experience with Dynamic Scroll Page Transition

Hey everyone! I've been working on revamping a website and stumbled upon this fascinating page transition that I would love to replicate. However, I haven't been able to find a JQuery library that can achieve this effect. Does anyone have any i ...

Tips for shifting a fabricjs element generated within a nextjs useState hook?

I encountered an issue where creating a fabric canvas in a useEffect() function prevents me from moving the added images. However, if I create the canvas elsewhere (even though it may be subject to useState asynchrony issues), I am able to move the image ...

Template not rendering array data correctly in Meteor

Here is an example of the array structure: var myarray = [ device1: [ name:device1 , variables: [ variable1: [ name: variable1, unit: "a unit", ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...

The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but ...

How can you maintain the "link" text in a div while removing the final hyperlink?

I am currently designing a breadcrumb navigation for a website. The breadcrumbs are generated using a templating language before the page is displayed. However, after rendering the page, I need to make some adjustments. Instead of using multiple IF/ELSE s ...

Retrieving Form Validation Error Value in AngularJS

Incorporating AngularJS 1.2 RC2 and utilizing Bootstrap for CSS, I have constructed a straightforward form as shown below: <form class="form-horizontal" name="form" novalidate> <label class="col-lg-2 control-label" for="name">Name</labe ...