AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models?

Here, the OP demonstrates using ngOptions with parent/child relationships.

template

<select ng-model="x.site" ng-options="s.site for s in data"></select>
<select ng-model="x.name" ng-options="b.name for b in x.site.buildings"></select>

controller

$scope.x = {};
$scope.data = [
    {
        "site" : "Brands Hatch",
        "buildings" : [
            { "name" : "Building #1" },
            { "name" : "Building #2" },
            { "name" : "Building #3" }
        ]
    },{
        "site" : "Silverstone",
        "buildings" : [
            { "name" : "Building #4" },
            { "name" : "Building #5" },
            { "name" : "Building #6" }
        ]
    }
];

In this fork, the dropdowns have default values as "blank". Typically, this is not an issue and defaults can be set easily through the controller as explained in the documentation.

  • How can I remove the "blank" options for parent/child models using ngOptions?
  • How do I select default options either from the view or dynamically from the controller? It's important to note that child default select options depend on the parent's selected option.

Answer №1

To fix the issue of the blank item, ensure to set an initial value for site, building, and floor in your controller. You can use the code snippet below at the end of your controller. This will initialize the values when the page loads and also update them when the site value changes. I hope this solution helps resolve the problem.

$scope.selected = {
    site: $scope.data[0],
    building: $scope.data[0].buildings[0],
    floor: $scope.data[0].floors[0]
};

$scope.$watch('selected.site', function () {
    console.log($scope.selected.site);
    $scope.selected = {
        site: $scope.selected.site,
        building: $scope.selected.site.buildings[0],
        floor: $scope.selected.site.floors[0]
    };
});

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

Accessing values from an array within a JSON object using jqGrid

Here is an example of my JSON data: [{"codDiretor":"123", "nomeDiretor":"Nome do Diretor", "data":"29/01/2014", "documentos":[{"codDocumento":"1", "nomeDocumento":"Primeiro Doc"}, {"codDocumento":"2","nomeDocumento":"Segundo Doc"}] ...

Exploring AngularJS: Retrieving data based on a specific ID from a JSON document

Within my controller class, I extract the ID of a specific user from the URL and pass it on to the OrderService. My goal now is to fetch the data associated with this ID from a JSON file. How can I accomplish this task? OrderCtrl 'use strict'; ...

Implementing the requiredUnless validator of vuelidate for checkboxes: A step-by-step guide

When utilizing Vuelidate, the 'required' validator now accepts boolean 'false' as a valid value. To enforce required validation for checkboxes, you must use 'sameAs' such as sameAs: sameAs( () => true ). How can 'requi ...

Quickly align with vertices using threejs

As I delved into creating a snapping feature to align with my mesh vertices, I embarked on multiple trial-and-error solutions. One method involved introducing THREE.Sprite instances for each vertex in the scene and utilizing a rayCaster to determine if th ...

Adjust Div Width using a button press

I am attempting to create a functionality where an iFrame will resize in width upon clicking a button. My goal is to have multiple buttons representing breakpoints such as 1024, 680, 480, 380 pixels where the iFrame will adjust its size accordingly. Unfort ...

Stopping a jQuery AJAX request after receiving another response

I am facing a problem and I need some creative solutions :) Currently, I have two $.ajax calls in my code. The first call is asynchronous and takes a long time to respond (approximately 1 minute). On the other hand, the second call is synchronous (with as ...

Tips for optimizing performance by preloading external CSS and JavaScript files from a third-party source in a ReactJS project with webpack

Is there a method similar to using ProvidePlugin for preloading jQuery that can be used to preload third-party CSS and JS files without using import in the entry JS file? The reason I am interested in preloading these files is because I encountered an err ...

Javascript isn't being executed by Internet Explorer as expected

I'm currently working on a web application that requires backend processing while simultaneously showing the information on the screen. AJAX seems like the ideal solution, so I've implemented it in my project. However, before initiating the AJAX ...

Executing a jQuery function automatically & Invoking a jQuery function using the onClick attribute in an HTML element

Having some issues with jQuery and could use some assistance... Currently, I am trying to have a jQuery function automatically execute when the page loads, as well as when a button is clicked. [Previous Issue] Previously, the jQuery function would automa ...

Failed to execute npm script for server side rendering (ssr)

I experimented with Server-Side Rendering (SSR) in my React application for SEO benefits. Although I encountered certain errors, they were not considered actual errors by React. Initially, the error appeared in componenDidMount=()=> Upon commenting ou ...

The conditional rendering logic in the ng-if directive does not seem to be synchronizing

Currently, I am delving into AngularJS and working on a basic application to gain familiarity with it. Within my app, there are four tabs: List, Create, Update, and Delete. However, my goal is to only display the Update and Delete tabs when I press the b ...

"Encountering a problem with the client-session middleware: the value of req.session_state is becoming undefined

I'm facing an issue with client-session middleware in Express. After setting the session_state, it doesn't seem to be accessible when redirecting to a new route. I followed a tutorial on YouTube (client-session part starts at around 36:00) and do ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Using C# ASP.NET to create an array that corresponds to a JavaScript array

I am trying to figure out how to assign an array in my C# code behind and call a JavaScript function that uses that array. The JavaScript function looks like this: <script type="text/javascript"> var TotalData = new Array(); function S ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

Initiating a SOAP request to utilize your custom services

Currently, I am in the process of creating a web application that includes providing various web services. After completing the domain model, we are now focusing on implementing both the User Interface (UI) and controller. The controller will consist of t ...

Trouble with Callback firing in Select2's 'Infinite Scroll with Remote Data' feature

After reviewing the tutorial on the Select2 project page, I am implementing a feature to load additional records as the user scrolls to the end of the results. <script> $(document).ready(function() { $('#style_full_name').select2({ ...

Is there a way to retrieve a zip file through angularjs?

Currently, I am utilizing AngularJS and receiving a zip file URL from the server. The code snippet below is what I'm using to initiate the download of my file. <a href="{{filename}}" download="{{filename}}">Example 1</a> The filename is ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

Access information through the restful api using the angularjs service $resource

I am attempting to utilize the $resource service with the surveygizmo API. Here is my code: HTML : <div ng-app="Survey"> <body> <div ng-controller="SurveyCtrl"> {{survey.data.title}} </div> </body> </div> My scr ...