Angular.js: automatically select default option based on ID

In my angular.js single page application, I am retrieving initial data from a rest endpoint.

The data consists of a list of IDs representing saved models and a tree of options for cascading dropdowns.

How can I automatically set the default path in the tree based on the IDs from the model?

Here is some sample code:

Models:

DefaultOptions = [
    {"Id" : 044},
    {"Id" : 142},
    {"Id" : 244}
];

OptionsTree = [
    {"Text" : "Option1",
     "subOptions" : [
          {"Text" : "SubOption1", "Id" : 044},
          {"Text" : "SubOption2", "Id" : 142}
      ]},
    {"Text" : "Option2",
     "subOptions" : [
          {"Text" : "SubOptionA", "Id" : 3033},
          {"Text" : "SubOptionB", "Id" : 244}
      ]}
];

HTML:

<div ng-repeat="member in DefaultOptions">
    <select ng-model="option" 
            ng-options="o as o.Text for o in OptionsTree">
    </select>

    <select ng-model="subOption" 
            ng-options="s as s.Text for s in option.subOptions"
            ng-disabled="!option" 
            ng-change="member.Id = subOption.Id">
    </select>
</div>

While this HTML code successfully updates the ID in DefaultOptions when a new selection is made, it does not set a default. What is missing here?

Answer №1

Make sure to update your ng-model in your selects to match the ng-repeat:

Incorporate the following code snippet into your controller:

// Main dropdown
$scope.member.option = OptionsTree[0];

Followed by:

// Sub dropdown
$scope.member.subOption = OptionsTree[0].subOptions[0].id

Since it wasn't specified in your question, I assumed you wanted the id for the sub dropdown and the whole object for the main dropdown.

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

remove MongoDB entry using unique identifier

I am currently working on a blog project using nodejs, express, and mongodb. My goal is to delete a specific document by its ID. For instance, if I want to remove a blog post with the ID 52976b1b0855c7e81a6192e9, I would make a request to localhost:3000/bl ...

Guide to ensuring modal box only appears once all criteria are satisfied

On my website, I have a form that requests the user's personal information. After filling out the form, a modal pops up with a "Thank you for signing up" message. The issue is that even if all fields are left blank and the button is clicked, the modal ...

The WHATWG URL API allows creation of a new URL using the new URL

I've been experimenting with node and attempting to create an instance of the URL class to utilize its useful properties. Here's what I tried: const { URL } = require('url'); (...) http.createServer((request,response) => { let u ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

jQuery when - anticipate the fulfillment of multiple success/done callbacks

When using $.when to determine when an array of ajax promises are finished, I have noticed that although the ajax calls themselves are completed when $.when fires, their callbacks and done functions are not. How can I make sure to wait for the callbacks to ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Creating dynamic routing functionality in Angular 8 allows for a more personalized and

I am struggling with setting up routing in Angular 8. Here is how I am trying to do it: 'company/:id/activity' 'company/:id/contacts' However, I am not receiving any params in the activatedRoute: this.activateRoute.params ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

User interface failing to refresh after fetching data with AJAX

I have been working on a restaurant app and here is the code snippet: // Select date and load resources $scope.selectDate = function (date) { $scope.dateInActiveSelection = date; loadMenuFor(date); }; // Load daily menu fo ...

Ways to designate a parent element in Vue Draggable when the element is lacking a child

I'm currently incorporating vue-draggable into my project from the following GitHub repository: https://github.com/SortableJS/Vue.Draggable Below is my ElementsList component: <div> <draggable v-model="newElement" :move ...

Has the rotation of the model been altered?

Is there a way to detect if the rotation of a model has changed? I've attempted: var oldRotate = this._target.quaternion; console.log('works returns vector3 quaternion: ', oldRotate); var newRotate = oldRotate; if (oldRotate != ...

Should the use of readFileSync() during the initialization of a Node.js web application be avoided?

I have a Node app that serves web pages with static HTML-snippet files included conditionally. I am considering implementing a cache map for these snippets by adding the following code to my Express's app.js file: var cache = Object.create(null); cac ...

What is the best way to submit several files along with additional fields simultaneously using FormData?

I have a collection called pocketbase that consists of fields like name, image, and order. My goal is to upload all the images with unique names and in parallel using the power of FormData. Take a look at my code below: export default function AddPhotosAd ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

Is it feasible to pre-load external websites using JavaScript?

While searching on various platforms, including Stack Overflow, I couldn't find a solution to this specific query. I'm not necessarily seeking an implementation already in place, but rather ... Imagine having an intranet application that loads q ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

Material-UI React is unable to identify the `underlineStyle` property on a specific HTML element

I tried implementing a custom style to change the underline color of a material-UI TextField element, following an example I found. http://www.material-ui.com/#/components/text-field Unfortunately, when I attempt to add my own styling, React does not rec ...

My goal is to ensure that when a user copies the URL of a website from the address bar and pastes it into a social media app, the link automatically transforms into the title of

Similar to the process in Airbnb where a copied URL is pasted in Slack and replaced with specific text along with the site URL I have tried adding og:title, description, and images, but cannot figure out how to handle this issue. Any assistance would be a ...

What is the most effective way to receive all values sent to an Observer upon a new subscription?

I have an observer that receives various values emitted to it at different times. For instance sub = new Subject<any>(); sub.next(1); sub.next(2); sub.next(3); #hack 1 sub.next(4); sub.next(5); sub.next(6); #hack 2 If there is a ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...