Setting a default value in ng-options can be accomplished by using the ng-init

One way to set a dropdown list with a default value in AngularJS is by using the following code:

<select name="repeatSelect" id="repeatSelect" ng-model="repeatSelect" ng-init="repeatSelect = data[0].id">
    <option ng-repeat="option in data" value="{{option.id}}">{{option.name}}</option>
</select>

Alternatively, you can achieve the same result using ng-options. Attempting this method may look like:

<select name="repeatSelect" 
   id="repeatSelect" 
   ng-model="repeatSelect"
   ng-init="repeatSelect = option.id"  
   ng-options="option.name for option in data track by option.id">
</select>

However, if this second method does not work as expected, you can refer to a sample fiddle provided here.

Answer №1

Utilize the ng-init directive to establish a default value for the ng-options in AngularJS.

You can view the demonstration here: demo

<select name="repeatSelect" 
   id="repeatSelect" 
   ng-model="repeatSelect"
   ng-init=" repeatSelect = data[0].id"  
   ng-options="option.id as option.name for option in data">          
</select>

Answer №2

Using ng-init incorrectly.

The misuse of ngInit is highlighted in the Angular documentation:

ngInit can lead to unnecessary complexity in templates. It should only be used for specific cases such as aliasing properties in ngRepeat or passing data from server side scripting. In most situations, controllers should be used instead of ngInit for initializing scope values.

Source documentation

In my view, the best way to set a default value is to pre-fill your ng-model with the selected value from ng-options, letting Angular handle the rest.

When defining the $scope property, the select element will automatically bind to the default value from your data array. If the data comes from an AJAX request, simply assign it once the data is retrieved.

.controller('test', ['$scope', function ($scope) {
    $scope.data = [{name: 'one', id: 1}, {name: 'two', id: 2},{name: 'three', id: 3}];
    $scope.repeatSelect= $scope.data[0];
}]);

One thing to note is that when using the as keyword in your expression, you must assign your ng-model with the specific property to select.

For a complete demonstration, check out this fiddle showcasing both scenarios: http://jsfiddle.net/kb99gee8/

Answer №3

I successfully implemented the solution using your code and incorporating ng-options as you suggested. For a working example, please refer to this live demo

Complete CODE:

<div ng-app="ngrepeatSelect">
    <div ng-controller="ExampleController">
        <form name="myForm">
            <label for="repeatSelect">Angular select:</label>
            <select name="repeatSelect" 
   id="repeatSelect" 
   ng-model="repeatSelect"
   ng-init=" repeatSelect = data[0]"  
   ng-options="option.name for option in data track by option.id">
</select>
        </form>
        <br/> <tt>Selected value: {{repeatSelect.id}}</tt>

    </div>
</div>
<br/>

Answer №4

Here is an example of HTML code snippet:

<select class="form-control" ng-model="data.selectedOption" required ng-options="option.name as option.name for option in venueNamelists"  ng-change="getmediationRooms(data.selectedOption)"></select>

Within my controller:

$scope.data = {selectedOption: $scope.venueNamelists[i].name};

The value of the model should match the key,value pair within the venueNamelists.

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

Setting up computed properties in VueJSSetting up computed values in

I am currently working on developing a lottery number service, and I am curious about how to set up computed properties. I came across the Vue.js documentation for computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties. I tr ...

Troubleshoot: Issues arising when loading DataTables using AJAX with MYSQL

For some reason, I'm receiving an invalid JSON response from this code. The objective is to showcase SQL data in a table with search and sort functionalities using https://datatables.net/. Can you pinpoint where the issue might lie? GET.PHP $mysqli ...

What is the best way to require users to click one of the toggle buttons in a form?

Is it possible to require the user to click one of the toggle buttons in a React form? I want to display an error if the user tries to submit the form without selecting a button. Even though I tried using "required" in the form, it didn't work as expe ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

Ways to transfer a jQuery variable value to a PHP variable

I am trying to transfer a jQuery variable value to a PHP variable on the same page using AJAX in my JavaScript code. I have attempted to print the PHP variable but encountered an error. Any assistance would be greatly appreciated. <script type="text/ ...

exciting, showcasing a dependency map using svg within an html5 environment

I am working on creating a polygon background for my menu, which needs to be responsive in design. Here is an example of what I am trying to achieve: example image. Should I use JavaScript to listen for size changes and adjust the points for the polygon e ...

The "results per page" ajax dropdown in Yii stops working after other ajax content is loaded on the page

One of the views in Yii framework is the "Patients" view, which contains several CGridViews and other elements that are loaded via ajax after the initial view has loaded. Some of these elements are nested within multiple levels of ajax-loaded divs. Within ...

@HostBinding in Angular 2 does not trigger change detection

When using @HostBinding in conjunction with Chrome's Drag and Drop API, the code looks like this: @Directive({ selector: '[sortable-article]' }) export class SortableArticleComponent { @HostBinding('class.dragged-element') ...

Encountering the issue of "unexpected error: autocomplete is not defined" when trying to retrieve information

I am using jQuery for retrieving remote data but encountering an error Uncaught TypeError: $(...).autocomplete is not a function. I have made several attempts, yet I cannot identify the root cause of this issue. It seems like there might be an error in ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

Why is MutationRecord[] organized as an array in MutationObserver?

I've been diving into the world of MutationObserve, and I've grasped most of it. However, one thing that's puzzling me is why the parameter requires an array. According to the documentation: An array of MutationRecord objects, detailing e ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

Instructions on how to make a radio button selected when clicked are as follows:

My radio button is currently checked, but I would like it to be onclicked because there is a Javascript function that uses the on.click function. Are there any possible methods or examples to achieve this? <label style="margin-left:177px;">Order Ty ...

Retrieving an attribute through the act of clicking a button

How can I retrieve the rel attribute value when clicking on a button with the class selector? <button class="nameClass" rel="relName">Content</button> I am attempting to achieve this by: $(".nameClass").click(function(){ // Here is where ...

The issue lies in AngularJS where updating data that is bound does not automatically update the corresponding template

Currently, I am in the process of building my very first mobile app using a combination of html5, cordova, angularjs, and jQuery. Initially, I had no issues creating my controller and template. The data that I bind to the template is retrieved from a .net ...

Setting up Visual Studio Code for debugging HTML and JavaScript code

Struggling to troubleshoot some HTML/JavaScript using VSCode. After installing the Chrome debugger extension and configuring the launch.json as follows: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of ex ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

How PHP Processes Fragment Identifiers within URLs

Looking for some advice from the community on a tricky situation I'm facing. Here's the issue at hand: I have developed a website with dynamic content pulled via AJAX and displayed using JS. To allow direct links to my content, I modify the frag ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: https://i.sstatic.net/lWL9Y.png Code Snippet: ...