What is the default value for a select element in Angular initialized with ng

I'm facing a challenge trying to set the default value for a select box. Despite my efforts, I can't seem to figure out what's going wrong. Here is the code snippet:

<select class="form-control" ng-init="newQuestion.positionOnSurvey=vm.questionsPositions[0]" ng-model="newQuestion.positionOnSurvey">
    <option ng-repeat="position in vm.questionsPositions track by $index" value="{{position}}">{{position}}</option>
</select>

The value of vm.questionsPositions[0] is 5, so that shouldn't be the issue. Although I am not initializing newQuestion in my controller, it should work with ng-init, right?

UPDATE:

I have updated my approach to initializing the field like this, but unfortunately, it is still not functioning as expected.

vm.newQuestion = {};
vm.newQuestion.positionOnSurvey = vm.questionsPositions[0];

<select class="form-control" ng-model="vm.newQuestion.positionOnSurvey">
    <option ng-repeat="position in vm.questionsPositions track by $index" value="{{position}}">{{position}}</option>
</select>

Answer №1

To properly initialize the value and create a drop-down list using ng-options, it is recommended to use a controller.

For example:

HTML:

<select class="form-control" ng-model="newSelection.choiceOnList" ng-options="choice for choice in vm.selectionOptions"></select>

Controller:

        $scope.vm ={};
        $scope.newSelection ={};
        $scope.vm.selectionOptions = [A, B];
        $scope.newSelection.choiceOnList = $scope.vm.selectionOptions[0];

This will set the initial value in the select list as A.

Answer №2

One approach you could take is to initialize the $newQuestion.positionOnSurvey variable in your controller with a default value. This way, the selector on the view will already have an initial value set.

Answer №3

It is essential to use ngInit only for aliasing special properties of ngRepeat. In all other cases, it is recommended to utilize controllers instead of ngInit for initializing values on a scope.

Based on the ngInit API, my recommendation would be to set the initial value of your selection in your controller.

for more information, refer to: controller guide

Answer №4

<select class="form-control" ng-init="vm.selectedQuestion.positionOnSurvey=vm.questionsPositions[0]" ng-model="selectedQuestion.positionOnSurvey">
                                    <option ng-repeat="position in vm.questionsPositions track by $index" value="{{position}}">{{position}}</option>
</select>

A new variable "selectedQuestion" is being initialized within the vm object, which can now be accessed in HTML as "vm.selectedQuestion"

Answer №5

Are you certain that ng-options isn't functioning correctly? Give this code a try.

<select ng-model="vm.newQuestion.positionOnSurvey" ng-options="position for position in vm.questionsPositions"></select>

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

Using the Angular two-way binding tag within a Spring Boot Thymeleaf application allows for seamless data synchronization between

I have a JSON file where my image is defined like this certLogoURL : "/img/ocjp.gif" I am attempting to show this image in my Thymeleaf template using the following code: <img th:src="@{ {{certificate.certLogoURL}} }" > </img> However, the ...

Vue: setInterval not updating timer variable

Here is my code for updating and displaying the number of elapsed seconds: <template> <div> {{timerValue}} </div> </template> <script> export default { name: "App", components: { }, da ...

Can someone help me locate the file using the inspect element feature?

Today, I encountered a small issue on my website that I wanted to fix. Although I was able to make the necessary changes using Inspect Element, I couldn't locate the file where it needed to be changed. The website in question is gesher-jds.org/giving. ...

Using Three.js to display a PerspectiveCamera with a visible bounding Sphere

My challenge is to create a Scene that loads a single .obj file where the object is fully visible in the PerspectiveCamera upon scene initialization. The field of view (FOV) is set at 60 The objects vary in size TrackballControls are utilized for camera ...

Exploring new possibilities in ChartJS with the use of multiple Y

I have successfully created a line chart using Chart.js with two datasets, each having its own Y scale and axis. The code for my datasets and options is as follows: datasets: [{ fill:false, label: 'Heat', yAxisID: "y-axis-1", da ...

What steps can be taken to utilize ajax for pagination and retrieving data efficiently?

My goal is to retrieve 3 specific data points from a webpage using the ajax get method. Here is the javascript code: <script type="text/javascript"> var busy = false; var limit = 15; var offset = 0; var id = 150; function displayRecords( ...

Adding static data along with fetched data in Vue.js: A simple guide

I am looking to include advertisement banners after every 5 items in the data displayed by my application. This means that for every scroll, you would see five fetched data items followed by an advertisement, and then another set of five fetched data items ...

AngularJS utilizes constants within other constants

If I define a constant using the code below: app.constant('appUtility', { primary: 'PrimaryColor', secondary: 'SecondaryColor' }); and then attempt to use it in another constant like this: app.constant('appUtil ...

Developing a fresh Chip with Autocomplete feature using Angular Material Design

I'm currently working with Angular Material Design and have implemented an autocomplete feature for a field that is populated with terms from an API call. However, I am facing an issue when trying to add a new title (chip) using md-transform-chip="vm ...

Upon page initialization, VueJS namespaced Vuex module getter does not properly return the expected value

Even in identical situations, I am receiving different outputs from the same getter function. console.log(store.getters); When checking the console, I see: {}: auth/loggedIn: true, which is the correct value. However, when specifically accessing this get ...

Adding new data to a Chart.js line graph in vue on form submission - A step-by-step guide

I'm struggling with dynamically updating my line chart with new data. I want the chart to refresh every time a user submits a form with new data. Currently, I can add new data to the datasets array in the data function of App.vue, but the chart doesn& ...

Tips for conducting unit tests on navigator.notification.alert

I am currently facing a challenge in writing a unit test for a JavaScript function where I need to fake the navigator.notification.alert method. Can anyone provide suggestions or solutions? Below is the code snippet that I have attempted: navigator = { ...

Storing and Editing Collection of Elements

My latest project involves creating a basic web scraping tool that gathers information on apartment prices from a specific webpage. Each time the tool runs, it compiles an array of objects with details such as date, time, floor plan name, bed number, floor ...

What could be causing the misalignment of my request and response messages?

Currently, I am going through a Node.JS basics book and have successfully created two programs - one responder and one requester. The responder: "use strict"; const fs = require("fs"); const zmq = require("zmq"); const responder = zmq.socket("rep"); // ...

Fitting Bounds in Angular with Google Maps

Can anyone help me with calling the fitBounds() method from an angular-google-maps instance? I'm struggling to figure out how to do it after uiGmapGoogleMapApi resolves. In the vanilla js implementation, you can use map.fitBounds(bounds), but I'm ...

Revamp the HTML table with JavaScript headers

I imported data from a CSV file into an HTML table and here is how it appears: <div id="myTable" style="-ms-overflow-x: auto;"> <table> <tbody> <tr class="rownum-0"> <td>Make</td> ...

Utilize Node Package to Dispatch Firebase Push Notifications

I am currently experimenting with a NodeJS module for sending Push Notifications. I have been exploring the 'node-sender' module but have not been able to find an option for sending notifications to a web browser for testing purposes: https://w ...

Using Javascript to assign a hidden form value when the drop down selection changes - having trouble populating options from an array in Javascript

When using my JavaScript code to create 2 arrays for Product Category and Product selection, I encountered an issue. The user must first choose the type of Campaign they want to run before selecting the Product Category or Product. The 'Campaign' ...

Problems with JQuery Ajax Json Response

Provided Form Section: <script type="text/javascript" src="js/aboneol.js"></script> <h4>Subscribe</h4> <div class="newsletter"> <span id="aboneolerror">< ...

"Upon subscribing, the array within the object is found to be

I am encountering a synchronization issue while trying to retrieve an element after making multiple HTTP requests. Below is the code I have posted: Get function in my service: get() { return new Observable(project => { this.channelsService.get().sub ...