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

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Steps for creating bold headers when exporting data as a CSV file using alasql:

How can I make the headers bold when exporting as CSV using alasql? var data = [ ["FirstName", "LastName"], ["Alan", "Tsai"], ["John", "Doe"] ]; var jsonData = [{ "FirstName": "Alan", "LastName": "Tsai" }, { "FirstName": "John", "LastName": ...

Ag-Grid is failing to display MenuTabs

I need help getting the columns menu tab to appear in Ag-Grid. It should be a simple task. I want both the general and columns tabs, similar to the demo shown here Currently, when I specify both tabs, only the general tab is displayed. If I specify just t ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

When trying to install express using Node.js npm, an error message 'CERT_UNTRUSTED' is preventing the installation of express

My goal is to set up express on Raspberry Pi for the purpose of using it in a REST API. However, I keep encountering an issue with SSL certification when trying to install it through npm. Despite attempting various solutions found on different forums, I ha ...

What are the steps for accessing a server-side WebControl from the client side?

Issue Overview: I am facing a problem with managing different types of input values in my dialog box. Depending on the selection from a dropdown list, the required input could be simple text, a date, or specific data from a database. I have successfully i ...

Unlocking Bootstrap variables in Vue development (using Vanilla Bootstrap)

What is the best way to customize or theme bootstrap? I have heard that using sass to override bootstrap variables is recommended, but how can I integrate this into the Vue webpack workflow? I tried searching online and found suggestions to edit the vue.c ...

Express fails to pass password validation

I encountered an issue with a ValidationError stating that the Path password is required while attempting to register a new User. My experience in Node, programming, and authentication is limited. Below is the code for the User model and schema where I ma ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...

Having trouble integrating an HTML template using JavaScript

I am currently attempting to integrate the HTML code of my website using data-prototype: <div id="accordion" data-prototype=' <div class="card-body"> <textarea id="solution_answers___name___content" name=& ...

Send the function with parameters, but do not pass its output

Within my component, there is a need property that holds a static function. This function is executed by middleware to handle asynchronous API calls before rendering the component. Here's an example: static need = [ myFunc(token) ] The issue arise ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

Add a component to another component in real-time

Check out my StackBlitz demo: DEMO I'm attempting to insert the 'table' component into the #test section of the app component when the visualization type is 'table'. To achieve this, I am using the createTable() function which gen ...

Searching with Neo4j, Java and the Angular library for accurate

When my web application is opened, it displays a form where users can input a list of comma-separated usernames. The application then queries the neo4j database to fetch information for each username. I am interested in implementing autocomplete functiona ...

Exploring the methods of accessing $scope within an AngularJS directive

My custom directive is designed for handling form controls like input, select, and radio buttons. Each input has a default value set, and if the corresponding value exists in $scope.answers, it should be displayed in the input box. The code snippet below ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

What sets Fetch apart from ajax and XMLHttpRequest that makes it impressively faster?

Over the past few days, I have been working on optimizing a client table for a project. The table contains over 10k clients, and as a result, it was taking a long time to load. The front-end team had implemented pagination, filters, and reordering, which ...

Angular js for verifying emails

I have been studying Angular on W3Schools but I am having trouble understanding a particular piece of code. The code can be found at http://www.w3schools.com/angular/angular_model.asp <form ng-app="" name="myForm"> Email: <input type="ema ...