Tips for updating the text shown in an md-select box without affecting the underlying model

Using the Angular material library directive md-select, I have implemented a feature to display country codes to users. When a country is selected, I want to show only the country's dialing code in the select box.

For example, if the user selects India (+91), the select box should display +91 as the text. The code I am currently using is:

<md-select ng-model="ctrl.selectedCountry" ng-model-options="{trackBy: '$value.code && $value.name && $value.prefix'}">
        <md-option ng-repeat="country in ctrl.countries" ng-value="{{ country }}" >
                    {{ country.name }} ({{ country.prefix }})
        </md-option>
</md-select>

I am struggling to find a way to display only the dialing code in the select box without changing the ng-model binding. Is there a way to specify a display text template based on the selected value?

Answer №1

Give this a shot:

<md-select ng-model="ctrl.selectedCountry" ng-model-options="{trackBy: '$value.code && $value.name && $value.prefix'}">
        <md-option ng-repeat="country in ctrl.countries" ng-value= "{{ country }}" >
                    {{ctrl.selectedCountry.code === country.code ? country.name : (country.prefix + ' (' + country.code + ')')}}
        </md-option>
</md-select>

Answer №2

From version 1.0.8 of angular-material onwards, you can use the md-selected-text attribute, giving you the ability to implement the following:

<md-select md-selected-text="ctrl.selectedCountry.prefix" ng-model="ctrl.selectedCountry" ng-model-options="{trackBy: '$value.code && $value.name && $value.prefix'}">
  <md-option ng-repeat="country in ctrl.countries" ng-value="{{ country }}" >
    {{ country.name }} ({{ country.prefix }})
  </md-option>
</md-select>

Answer №3

Here is a clever css trick I came up with for md-select when using multiple selections. It's a great solution that works really well.

.option-hack {
  display: none;
}

md-option .option-hack {
  display: inline;
}
<md-input-container class="md-block">
  <label>Some Label</label>
  <md-select multiple
             ng-model="ctrl.array">
    <md-option ng-value="item" ng-repeat="item in ctrl.items" ng-selected="item.isOn">
      Always shown
      <span class="option-hack">Hidden on main</span>
    </md-option>
  </md-select>
</md-input-container>

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

Tips for creating a consistent header and footer across an HTML CSS web application

My previous projects involved using ASP.NET MVC and utilizing @Html.Partial("_header") to incorporate common static HTML across different pages. However, my current project is a pure HTML CSS and JS web app with no server-side technology. The la ...

Tips for preserving a string in angularJS or Java (and implementing it in an iframe)

My plan involves utilizing a Java web service to fetch the HTML content from a specific URL using Jsoup, and then returning it as a string to the requesting party, which could be an Angular or JS script. I am keen on preserving this content somewhere and l ...

Utilizing Freebase Suggest, is there a way to refine a field by the choice of another field?

When utilizing Freebase Suggest (), and having a field that chooses between Country or State, how can I make another "City" field filter to only display cities within that selected Country or State? In addition, if a user selects "New York" as their State ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Attempting to create distinct match matchups for every team in a manner reminiscent of the Swiss system format used in the 2024/25 UEFA Champion League

I've been working on devising a tournament pairing system modeled after the updated UEFA Champion League structure. The league phase involves 36 teams, categorized into 4 different pots. Each team is scheduled to play a total of 8 matches against 2 op ...

How does the system automatically update the ordered list (1, 2, 3) when some list items are removed in between the numbers?

After removing an item, the order of list numbers is automatically updated but the item numbers are not synchronized with those numbers. I want the item numbers to be synced with the li numbers. "use strict"; var demo = angular.module("demo", []); fun ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

How can I show the number of items in my filtered data using AngularJS?

My data array holds objects in JSON format. var users = { 'New':{ {Name:'One'}, {Name:'Two'} }, 'Old':{ {Name:'Three'}, {Name:'Four'} } This piece of code is used to disp ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

Utilizing Angular's ng-show feature alongside an AJAX request to retrieve specific information

As a newcomer to Angular, I am currently working on setting up a notification list. The concept is straightforward - a summary of notifications is shown and when clicked, the details of the notification appear. You can see what I've done so far in thi ...

Resolving peer dependency conflict during npm installation

When attempting to run npm install @react-navigation/native @react-navigation/native-stack, I encountered the following errors: npm WARN ERESOLVE overriding peer dependency npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While ...

Is there a way to continually update a specific portion of a webpage using AJAX without manual intervention?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10"); while($message = $db->fetch_array($messages)) { $oldMessage[] = $message['message']; } $oldMessages = array_reverse($oldMessage ...

Guide on transferring input element to h3 tag without using the URL

Is there a way to update the h3 tag every time a user clicks without updating the tab URL? I only want to update the h3 tag. I have attached all files and a screenshot of the URL. <!DOCTYPE html> <html> <head> </head> ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

Is there a way to add text to HTML code using CKEditor?

I incorporate CKEditor into my website. When I click on a specific link, it adds some text to the editor successfully. However, when I switch to the source tab, I am unable to append this text to the existing source code. Can anyone offer guidance on h ...

What are the steps to add a Search Box to my HTML Website?

Currently, I am in search of a way to incorporate a "Search" feature on my website that is built solely with HTML. I have added a Search box for the users but I'm uncertain about how to proceed next. Can I use PHP to enable the Search functionality o ...

What is the best way to load the route calculation dynamically?

I am struggling with calculating the Google Maps route dynamically. The console shows an error stating that 'calcularRuta' is not defined: Uncaught ReferenceError: calcularRuta is not defined at HTMLInputElement.onclick (index.html:1) Despi ...

Troubleshooting Guide: Issues with Bootstrap 3 Modal Window Implementation

This question is so simple that it's embarrassing. I attempted to copy the code from http://getbootstrap.com/javascript/#modals directly into a basic page setup, but it's not functioning. It seems like I'm making a very silly mistake. Here i ...

Using Angular to make a call to the BBC radio API

Looking to retrieve this JSON data from BBC Radio? You can find it at While you might be able to access it through POSTMAN, encountering errors when trying to fetch it from your Angular app is a common issue. When attempting to load http://www.bbc.co.uk/ ...