How to set a default value in AngularJS ng-model using the value from another ng-model

One of the challenges I'm facing is transferring a value set by the user in an ng-model from one form field to another ng-model as the initial value within the same form.
For example, I want the ng-init value of myModel.fieldB to be the value myModel.fieldA.subfield. This evaluation is working successfully in the value displayed within the span element. However, it's not updating the ng-model for myModel.fieldB, meaning that

ng-init="myModel.fieldB = myModel.fieldA.subfield"
isn't functioning as expected.
Strangely enough, when passing string literal values, such as in
ng-init="myModel.fieldB = 'some example'"
, everything works correctly.

<span class="form-group" ng-model="myModel.fieldB" ng-init="myModel.fieldB = myModel.fieldA.subfield">{{myModel.fieldA.subfield}}</span>

Answer №1

The reason for this behavior is that when you pass a literal value, it remains constant and does not change. However, if you pass a variable value like

ng-init="myModel.fieldB = myModel.fieldA.subfield"
(myModel.fieldB), it will be initialized only once upon the creation of the element with whatever value is inside (myModel.fieldA.subfield). To work around this limitation, you can use ng-change on the select element as shown below:

<select data-ng-model="myModel.fieldB" ng-change="myModel.fieldA.subfield = myModel.fieldB">
   <option value="option1">option1</option>
   <option value="option2">option2</option>
</select>
<span class="form-group">{{myModel.fieldA.subfield}}</span>

Answer №2

Is it possible to utilize the ng-change directive for your select input, where you set the value of myModel.fieldA.subfield to be equal to myModel.fieldB?

Here's an example:

ng-change="assignValue(myModel.fieldA.subfield)"

Then:

$scope.assignValue = function(val) {
    if (val) {
      $scope.myModel.fieldB = val;
    }
  }

For a demonstration, check out this plunker

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

Is there a method to prevent Google Maps from resizing when the DOM is altered?

I am currently facing performance issues with my Ionic app on Android. The opening animation for modals is slow, and after using Chrome timeline, I discovered that the Google Maps resizing and re-rendering process is causing lags in the modal animation. ...

Trouble Connecting Local Database with PG NPM Package

I'm encountering issues with using the pg package on my computer. I've attempted to execute the following code: var pg = require('pg'); var con_string = "postgres://user:password@localhost:5432/documentation"; var client = new pg.Clie ...

The simple-ssh Node has successfully completed its operations without encountering any errors

I'm having trouble establishing a connection to an Ubuntu EC2 instance using the Node library called simple-ssh. Below is the code snippet I'm using: const SSH = require('simple-ssh') const fs = require('fs') var ssh = new ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

Passing a table value to a PHP script using JQuery on click event

I am struggling with implementing functionality to filter a dataset based on the link that the user clicks on within a bootstrap modal. The modal contains a morris.js graph and I need to pass the clicked value (e.g. Cluster1 or Cluster2) to a data pull scr ...

Tips for placing multiple images onto one canvas

I am currently working on a web application that allows users to create sketches, define their positions and sizes, and then save them to a database. In another section of the website, I aim to retrieve these images and display them on a single canvas. To ...

Utilize ngFor in Angular Ionic to dynamically highlight rows based on specific criteria

I'm working on an application where I need to highlight rows based on a count value using ngFor in Angular. After trying different approaches, I was only able to highlight the specific row based on my count. Can someone please assist me? Check out m ...

Is there a way in Angular 1.5 to compile the HTML of a parent component from within a child component?

I have created two angular components called app-menuitem and app-menu. The app-menu component contains a list of app-menuitems as its children, without using transclude. App-menuitem Component: angular.module('app') .component('appMen ...

Experiencing difficulty with implementing an Angular filter to search through a list

Currently, I am utilizing an angular filter to search through a list. The searching functionality using the filter works as expected. However, I have encountered an issue with a checkbox labeled 'Select All'. When I search through the list and on ...

Exploring Methods to Iterate through an Object Utilizing Two Arrays

Attempting to iterate through states passed as props in another component state = { question:[firstQ, secondQ, thirdQ], tag:[[1,2,3],[4,6],[a,b,c,d]] } I aim to display it on the next Componet with a pattern like: FirstQ [tag1] SecondQ ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Does Angular's $pristine functionality work effectively with nested input fields in forms?

My form is causing me some problems. Two main issues I'm encountering: 1 - When trying to check for $pristine on the form using console.log($scope.myFirstForm.$pristine);, I keep getting the error message: `cannot read property '$prestine' ...

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

Organize a collection of objects based on their individual keys

How can an array of objects be grouped based on keys using vanilla JavaScript, especially when dealing with a large number of records like 10000? Here is a sample object to illustrate: [ { company: "TATA", car: "TATA Indica", color: "Blue" }, { ...

Navigating Next.js: Mastering the art of localStorage Access

Currently, I am developing my first member area using next.js. My goal is to store some data in localStorage (such as token, expiresAt, userInfo), which will eventually be moved to an http-only cookie. The code below is generating the error: "LocalStorage ...

Exploring the Scope of LocalStorage in Javascript

I've recently begun working with local storage and encountered some scope issues. Whenever I try to console.log(test), the second if statement returns undefined. What am I missing here? This is my current code; $("document").ready(function(){ ...

How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API. Here is the image: Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetical order, the data will be arrang ...

Getting directions using the node-googlemaps module in node.js can be achieved by following these steps

For the past day, I've been attempting to make progress with this Node.js Google Maps directions example, but so far, no success. Every time I run it, I keep seeing ·· √ OK » 2 honored (0.848s). I've previously asked a similar question on U ...