How to automatically adjust select view in AngularJS as model value is updated

My select element is structured as follows:

<select data-ng-model="transaction.category"
            class="form-control"
            data-ng-options="category.name group by category.parent for category in categories"
            required>
    </select>

The model transaction is initialized like this:

$scope.transaction = {};

To set values, I use the following syntax:

var transaction = new Transaction();
transaction.name = $scope.transaction.name;
transaction.category = $scope.transaction.category.uuid;

This is how the categories are structured:

[  { 
name: Alcohol & Bars
parent: Food & Drink
uri: /categories/9b1e97f2-ac7d-4caf-85fc-476cd97dd6cb
uuid: 9b1e97f2-ac7d-4caf-85fc-476cd97dd6cb
 } ,  { 
name: Coffee & Tea
parent: Food & Drink
uri: /categories/cf040e77-2faa-41de-b9f7-3749a42735ac
uuid: cf040e77-2faa-41de-b9f7-3749a42735ac
 } ...
]

Although everything works fine when selecting a value from the drop-down, there is an issue that arises.

What seems to be the problem?
In certain scenarios, I need to set the category based on user preferences that have been pre-populated.

How do I tackle this situation?
I implement the following code snippet:

$scope.templateSelected = undefined;
$scope.$watch('templateSelected', function () {
    if ($scope.templateSelected !== undefined) {
        $scope.transaction.category = $scope.templateSelected.category;
    }
}, true);

Expecting the HTML select options to be automatically selected, but unfortunately, this does not happen as anticipated.

So, what's the question here?
How can I update my select option based on $scope.templateSelected.category?

UPDATE:
The structure of Transaction is defined within AngularJS like this:

angular.module('transactionService', ['ngResource']).factory('Transaction', function ($resource) {
    return $resource('/user/transactions/:transactionId',
        {transactionId: '@uuid'},
        {
            getRecent: {method: 'GET', params: {recent: true}, isArray: true},
            getForYearMonth: {method: 'GET', params: {}, isArray: true}
        });
});

Answer №1

By default, angular keeps track of the selected value in a <select> element based on the reference of the object.

When you assign

$scope.transaction.category = $scope.templateSelected.category;
, the $scope.transaction.category does not exist as an object in the list.

To instruct angular to identify the selected value based on a specific property, you can use track by category.uuid:

data-ng-options="category.name group by category.parent for category in categories track by category.uuid"

DEMO

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 it necessary for a click handler to be triggered when clicking on a scrollbar?

Check out these HTML snippets: Jsfiddle <style> div { margin:20px; border: 30px red solid; padding: 20px; background-color:green; overflow-y:scroll; } </style> <div onclick="alert('div clicked');"> ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

Combining video.js and vue.js for seamless integration

Can anyone guide me on how to display a youtube video using a video.js player within vue.js? I'm new to integrations and not sure what it entails. Any assistance will be greatly appreciated. ...

Jade incorporates a template that is dependent on a variable

Is there a way to incorporate a template that is dynamically named based on a variable? For example: include= variableTemplateName ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

Preloading error alert message displayed during AJAX request

When I send an ajax request with a dropdown change, the loader div is shown using "before send". However, the issue is that the loader only displays for the first time, even though the ajax functionality works all the time. If you want to check this issue ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

Unable to navigate to partial view within MEAN application

I'm currently following a tutorial on creating single page applications using the MEAN stack. So far, I have successfully rendered the index.jade view. However, I encountered an issue when trying to route to a partial view as the DOM of the page does ...

Utilize JSON to create a dictionary populated with objects following a complex grouping operation

I am faced with a JSON query that contains the Date, Value, Country, and Number fields. My goal is to create two separate JSON dictionaries based on unique dates (there will be two of them). The desired output can be seen in the code snippet below along wi ...

How can you access additional fields beyond what is displayed in a dropdown select menu in React?

I am working with an array of Jsons that contain the fields ID, name, and description. My goal is to create a dropdown selection box that will show both the name and description when clicked, and then store the associated ID in the rawID state. I have been ...

Utilize data fields beyond the export default in Vue

Is there a way to access the information stored within the export default in my Vue component's JavaScript file? Specifically, I am trying to retrieve the contents of the routes array within the calculateAndDisplayRoute() function. overview.js funct ...

Tips on securely saving passwords using Greasemonkey

Created a custom userscript that prompts users to save their login credentials in order to avoid entering them repeatedly. Familiar with using localStorage.setItem() to store key-value pairs, but concerned about storing passwords in clear text. Seeking ad ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

Collaborating on a single instance across several processes

I have a messaging bot in my project, where the connection is established using a class instance. class MessagingBot { public bot; constructor() { this.bot = new TelegramBot(); } } export default MessagingBot; In another file, I create an inst ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Topaz font does not properly display backslashes and certain characters when rendered on Canvas

Who would have thought I'd stumble upon a new challenge on Stack Overflow? But here we are. If there's already a solution out there, please guide me in the right direction. I'm currently developing an interactive desktop environment inspired ...