Pre-selected default value in select box using ng-options

I'm working on setting a default value in my select box, retrieved from the database, using ng-options.

Here's my view:

<select class="form-control samlength modalinput" 
        ng-options="p.procid as p.procname for p in processes track by p.procid" 
        ng-model="p.procid">
  <option value="">-- choose an option --</option>
</select>

The value p.procid corresponds to data from the database.

My dataset:

procid  procname    time
    1   MyProcess   2018-05-30 13:34:54.097 3003162
    3   Testing     2018-05-31 18:31:32.467 3003162

If I want to pre-select procid as 3 by default, how can I achieve this?

For your information - I've tried various solutions suggested in other discussions. Additionally, I attempted using ng-init, but without success.

Answer №1

To maintain your HTML structure, you can use the following code:

<select class="form-control samlength modalinput" 
        ng-options="p.procid as p.procname for p in processes track by p.procid" 
        ng-model="selectedProcess">
  <option value="">-- select an option --</option>
</select>

If there's a need to choose a specific item from the array, you can achieve this by searching through the array and matching the value at the specified key:

function findIndexByValue(arrayToSearch, key, valueToSearch) {
    for (var i = 0; i < arrayToSearch.length; i++) {
      if (arrayToSearch[i][key] == valueToSearch) {
        return i;
      }
    }
    return null;
}

Invoke this function like so:

var index = findIndexByValue($scope.processes, "procid", procid);
$scope.selectedProcess = $scope.processes[index];
alert(index);

Give it a try and hopefully it meets your requirements!

Answer №2

Make sure to update your HTML code like this:

<select ng-model="processSelected" 
     ng-options="p.procname for p in processes track by p.procid">
</select>

After that, initialize your model value in the controller as follows:

$scope.processSelected = $scope.processes[1];

Remember that $scope.processes represents an array of process objects.

Check out this Plunker Example

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

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Creating an unsorted list from information in a database table: A step-by-step guide

Hello, I am currently working on populating an unordered list with data from a SQL Server 2005 table. The table contains information about various applications like home, organization (with children such as policy and employee details), recruitment, help, ...

Invoke the ng-click function within the ng-change function

Just starting out with angularjs and I have a question. I am currently using single select and I want to retrieve the value selected and based on that value, perform an action. For example, if the value is "DELETE" then I would like to trigger the ng-clic ...

Choosing an option from a selection dropdown using Protractor

Struggling to navigate through my Angular-built application using the regular Selenium webdriver. I've added ngwebdriver dependency in pom.xml to resolve some issues, but can't figure out how to handle a specific drop-down on a page. Here's ...

What is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

It seems that there is an issue with accessing the root directory while utilizing the yo

I'm currently working on setting up the Yeoman 1.0 beta's angular scaffolding and have been following these steps in my workflow: npm install generator-angular generator-testacular # installing generators yo angular # creati ...

Comparison between SQL and jQuery regarding String Length Problems

I am facing an issue where the length of a string calculated using Sql Server (LEN) and jQuery ($(this).val().length) is different. The content of the string in question is as follows: 'Project Noida Ka-Rate Gr. Noida Ka AJNARA AMBROSIA-Sec. 118 ...

The changes to the grid options do not reflect immediately on the UI Grid interface

I am currently working on a project using the UI Grid module in AngularJS. I want to include row filtering as an option, but since not all users require it and the filter boxes take up a lot of space, I decided to disable filtering by default and add a but ...

Exploring Angular Applications with Search Engine Crawlers on ASP.NET

I am currently using AngularJS for my website's front end, and ASP.NET for the back end. I am in need of a headless browser that can easily render content on the server side for web crawlers. I have been looking into Awesomium.NET and WebKit.NET, bu ...

Tips for efficient navigation through posts when they are loaded via a JSON file

Check out my Plnkr demo: http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview Let's say I have a JSON file: { "info": { "test1": "test", "teste2": "test" }, "posts": [ { "name": "lorem ipsum", "content": "sit a ...

The attempt to initiate the MongoDB server was unsuccessful. dbexit reported an error with code 48 within the MongoDB system

After updating MongoDB, I encountered an error. I attempted to restart the MongoDB service, but the error persists. ...

Using the ng-change directive in an ng-repeat loop within AngularJS allows

Is there a way to cancel out the response in the answer field using an ng-change event on the dropdown box? I need a method to dynamically access the answer field. The code is within ng-repeat tags. For more information, please visit this PLUNKER. ...

The attempt to create the maq module was unsuccessful

I've hit a roadblock and can't seem to identify what I'm doing incorrectly in this code snippet. //app.js 'use strict'; var app = angular.module('maq', [ 'ui.router', 'maq.home.controller' ]).ru ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

Using AngularJS to Filter Array Elements

Here is a sample of the JSON data I am working with: products: [{ id: "1", model: "123", price: "123", spec: "213", image: "", brand: "213", category: "1", sub_category: "1", color: "1", size: "1", order: "1", ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

Distinguishing between {{::somevalue}} and {{somevalue}} in AngularJSIs there a

Hey everyone, I'm currently working on a project where I've come across two different syntaxes for data binding: {{::somevalue}} and {{somevalue}}. I'm not sure about the purpose of each one and couldn't find any information about it on ...

The animation in an AngularJS directive only functions properly when utilizing $timeout

I can't seem to figure out why the animation is not working as intended in the code below: app.directive('openMenu', ['$animate', '$timeout', function($animate, $timeout) { return { link: function(scope, elem ...

Unable to process form submission with AngularJS + Stormpath

I am facing an issue with form submission. Even though I believe that the login and password data are being sent correctly, nothing happens when I submit the form. I am attempting to submit the form without using ngSubmit because it is not feasible in my s ...