How can a default option be shown at the top of a select dropdown list in AngularJS with dynamic content?

Objective: Arranging a default <option> to always be displayed at the top of a <select> dropdown upon opening.

I am making progress towards my objective. We currently have a dropdown that dynamically populates based on selected elements, with the 'Text' option correctly appearing as default. I have implemented the orderBy: feature to sort the list alphabetically by their label, which was our initial requirement. However, we also want the 'Text' option to consistently appear at the top when the dropdown is opened.

This is the HTML code for the dropdown:

<select ng-options="t.id as t.label for t in currentOptions | orderBy:'label'" 
ng-model="rule.field" 
ng-change="updateOptions(rule, $index, true)" 
ng-init="updateOptions(rule, $index)" title="{{rule.label}}" 
class="form-control" style="width:100%" required></select>

The structure of the currentOptions array is similar to this:

currentOptions{"Text", "Banana", "Apple", "Notebook", "Coffee", "Zebra"}

Initially, the browser displays 'Text' in the clickable field since it occupies the [0] position in the array. When the dropdown is opened, the visible list appears as follows: "Apple" "Banana" "Coffee" "Notebook" "Text" "Zebra"

Our desired outcome is for the visible list to display as: "Text" "Apple" "Banana" etc.

Answer โ„–1

To adjust the orderBy option as needed, a custom function can be created. The function, named updateOptionOrder, simply checks if the current option label value is Text. If it is, the sorting process is skipped and the current option remains at the top; otherwise, default sorting based on the label value continues.

Check out this demo:

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
  $scope.currentOptions = [
      {label:'Text', id:'1'},
      {label:'Banana', id:'2'},
      {label:'Apple', id:'3'},
      {label:'Notebook', id:'4'},
      {label:'Coffee', id:'5'}, {label:'Zebra', id:'6'}
    ];
    
  $scope.updateOptionOrder = function(v) {
    if(v.label == "Text"){
       return -1; // Skip this sort for "Text"
    }else{
       return v.label; // Continue sorting based on label
    }
  } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="AppCtrl">
    <select ng-options="t.id as t.label for t in currentOptions | orderBy:updateOptionOrder" class="form-control" style="width:50%" ng-model="field"></select>
    <hr>
    <p>{{field}}</p>
  </div>
</div>

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

Struggling to understand how React js interacts with CSS files

While reviewing a React JS project, I came across some confusing CSS classes in the file. Classes like '.cards__item', '.cards__item__pic-wrap', and '.cards__item__img' were being referenced, but they weren't present in t ...

Setting up Ag-grid on AngularJS version 1.6 - A Comprehensive Guide

I went through the tutorial to set up agGrid for AngularJS with TypeScript instead of JavaScript. Here's what I did: npm install ag-grid var AgGrid = require('ag-grid'); AgGrid.initialiseAgGridWithAngular1(angular); var module = angular.mod ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Using RxJS for various scenarios with Angular HttpInterceptor

Take a look at the following code block containing AuthInterceptor: @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private authService: AuthService) { } intercept(req: HttpRequest<any>, next: HttpHand ...

Is there a way to individually invoke a function on every element within a webpage?

Every element in my database is accompanied by a distinct thumbnail for display purposes. To cater to user preferences, I have included a dropdown menu that triggers the display of different forms based on their selection through a function. However, my cu ...

Tips for dynamically adjusting PHP images based on screen size

I am facing issues with page speed due to the images I receive from the server. I am wondering if it's possible to request different image files based on the screen size that the page is being displayed on. I came across this code snippet: if( typeof ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

What is the best way to use jQuery to listen for a container resizing event?

I am confident that I can achieve this: $(window).resize(function() {funkyfunc();}); The above code will execute funkyfunc() whenever the window is resized. However, my issue lies in wanting to resize one control after another has been resized. I've ...

Using a variable in Ajax URL with Action razor syntax

I have a function that calls a method in the controller through an Action URL. However, I need to use a parameter as the name of the method, but unfortunately, this is not possible in the current implementation. function changeDropDownList(id, dropNameToC ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

Generating an interactive Datepicker using Jquery

How can I design a dynamic date picker similar to the image provided below? https://i.sstatic.net/euoNI.png I have attempted to create one, but I am looking for a more interactive date picker. Is there a way to achieve the design shown in the image? The ...

Configure unique headers for various environments

I am looking to customize headers like "id", "env", and "name" based on different environments in my application. Each environment has a unique set of values for these headers. I am struggling to implement this effectively within my existing code logic. T ...

Displaying a set through an express server cookie for the client to see

New to using Express and encountering issues with sending cookies. Created a basic express app that is supposed to set a cookie in the browser. Here's the server setup: const express = require('express'); const cookieParser = require(' ...

What is the process of establishing a "cache dependency" in local storage?

We currently utilize the local storage module from angularjs. https://github.com/grevory/angular-local-storage Does anyone have suggestions on how we can implement a cache dependency at the client side? We want to ensure that when data changes on the ser ...

How can the background of a div be altered when text is typed into an input field?

I need help with the following code. I want to be able to change the background color of a div with the class "target_bg" from red (default) to green every time someone enters or types text into the input field. <div class="target_bg"></div> & ...

Issues with JSON.parse in node.js on Windows 8.1 system

I've encountered an issue with the JSON.parse function in node.js on Windows, resulting in this error message in my command line: SyntaxError: Unexpected token ยดโ•—โ” at Object.parse <native> at R:\filelocation\server\server.js ...

Identify the transition of the parent element containing the <iframe> from a hidden state to a

Is there a way to identify when an iframe is shown after being hidden? HTML : <div style="display:none"> <iframe></iframe> </div> When the <div> is displayed using jQuery with $('div').show();, how can I determi ...