Angular JS dropdown with custom options

In our application, we have some dropdowns that cannot utilize the ng-options directive. This is because we need to set the title attribute directly on the <options> tag, which is not supported by ng-options.

The reason behind needing the title attribute is due to Internet Explorer versions older than 9 cutting off values that are too long. These values are only visible when the title attribute is present (showing up on hover of the element).

To understand the issue better, take a look at the following JSFiddle:

http://jsfiddle.net/nstuart/nF7eJ/ (HTML Bit)

<div ng-app="myApp" ng-controller="MyCtrl">
    <select ng-model="params.value">
        <option value="">Any</option>
        <option ng-repeat="v in options" value="{{v.value}}" title="{{v.name}}" ng-selected="{{v.value == params.value}}">{{v.name}}</option>
    </select>
    <p>{{params.value}}</p>
</div>

Currently, the select should have 'test3' preselected, but it defaults to an empty option instead. This occurs because the value of ng-model does not match any values in the ng-options list.

Any suggestions on how to resolve this issue? Is there a way to add titles to options generated by ng-options or any other solution available?

EDIT

I have updated the fiddle at: http://jsfiddle.net/nstuart/nBphn/2/ based on the feedback provided in the answer below.

Answer №1

Simply eliminate the curly brackets from the ng-selected expression to make it function properly:

<option ng-repeat="v in options" 
        value="{{v.value}}" 
        title="{{v.name}}" 
        ng-selected="v.value == params.value">{{v.name}}
</option>

View fiddle here

Answer №2

<option ng-repeat="v in options" value="{{v.value}}" title="{{v.name}}"
        ng-selected="checkOption(v.value)">{{v.name}}</option>

$scope.checkOption = function(value){
    return($scope.params.value == value);
}

Check out this Fiddle for more details!

[UPDATE] I initially forgot to pass the 'value' variable, but it has been updated now in the fiddle and this answer.

Answer №3

When using manual options, all you have to do is utilize the ng-model directive. This particular directive facilitates two-way data binding for the chosen option.

Check out the example on jsfiddle: http://jsfiddle.net/rpaul/1p9b5et8/1/

<body ng-app ng-controller="AppCtrl">
<select ng-model="selectedFruit" >
    <option value ='1'> Apple</option>
     <option value ='2'> Orange</option>
</select>
   The selected value is  {{selectedFruit}}
</body>


function AppCtrl($scope) {     

      $scope.selectedFruit = '1';
}

Answer №4

Consider exploring the select2 directive on

Answer №5

Within my coding, I recalibrate the chosen title whenever there is a change using ng-change="changeItem()"

CODE

<div ng-app="myApp" ng-controller="MyCtrl">
    <select ng-options="item.id as item.title for item in items" 
            ng-model="selectedId" ng-change="changeItem()" title="{{myTitle}}">
        <option value="" disabled selected style="display: none;">Choose an Item</option>                
    </select>
    <div>
        {{selectedId}}        
    </div>
    <div>
        {{myTitle}}        
    </div>
</div>

JAVASCRIPT FILE

angular.module('myApp', []);

function MyCtrl($scope) {

    $scope.items = [{
        id: 1,
        title: "Freezer"
    }, {
        id: 2,
        title: "Warmth"
    }, {
        id: 3,
        title: "Achievement"
    }];

    $scope.changeItem = function() {
        $scope.myTitle = undefined;
        for(var i=0; i<$scope.items.length; i++){
            if($scope.items[i].id == $scope.selectedId){
                $scope.myTitle = $scope.items[i].title;    
            }
        }    
    }    
}

Take a look at this Fiddle 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

Challenges regarding the CSS styling of the ui bootstrap modal and its compatibility with

Currently, I am in the process of developing a webpage utilizing angularjs and ui bootstrap to generate modals. However, as I attempt to print just the modal using javascript, I have encountered an issue with my CSS. It seems that due to potential formatti ...

The access-control-allow-origin header is failing to receive updates

I need help figuring out how to manually set the Access-origin header. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge& ...

Establishing the types of object properties prior to performing a destructuring assignment

Consider a scenario where a function is utilized to return an object with property types that can be inferred or explicitly provided: const myFn = (arg: number) => { return { a: 1 + arg, b: 'b' + arg, c: (() => { ...

"Refreshing the page is the only way to get the JavaScript image

I'm currently facing a frustrating issue with my game engine. The images are not loading correctly on the initial page load, forcing me to refresh the page every time. Here's the current code snippet that I'm working with: Texture creation: ...

Encountering a reference error while attempting to troubleshoot streamline.js generated JavaScript code

After successfully setting up streamline.js and generating code using _node --standalone -c stest._js, I encountered an issue. The generated code was not readable and debugging it in tools like Chrome's developer console seemed impossible. However, I ...

How can an Angular directive dynamically update template fields with the latest model values from the controller?

I am currently working with a <superhero> directive that includes two other directives: web-buttons, which handles form validation and posting the updated ngModel value to the respective controller. fieldMap, which generates dynamic fields based on ...

implementing CORS on an Express server for a specific domain

I am attempting to send a cookie post-login via AJAX from my localhost to a server that is hosted elsewhere. In order to prevent any errors related to cookies, I have included the following code in my Axios setup: var instance = axios.create({ withCr ...

Develop an ng-table that includes a dropdown menu allowing users to select the desired amount

I am looking to implement a dynamic ng-table with pagination, but I want the option to change the number of counts per page using a select box instead of buttons. Any suggestions on how to achieve this? Thank you in advance! ...

Development with Node JS, express, Mongoose, and intricate nested queries

I'm struggling with a group of interconnected queries using express/mongoose, structured like this: app.get(..., function(...) { Schema1.query(..., function(..., res1) { for ( var key in res1 ) { Schema2.query(..., function(..., ...

Having trouble getting Three.js JSON models to cast shadows properly?

Recently, I've been experimenting with blender exported models in Three.js. I have successfully imported a model and observed how light interacts with the object. While a directionalLight is illuminating the front-facing parts, I'm facing an issu ...

The phenomenon of componentDidMount being triggered before the DOM is fully mounted arises when utilizing createPortal in React

I have written a React code snippet that looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import ComponentB from './ComponentB'; class ComponentA extends React.Component { constructor(props) ...

Blog Writer: Picture quality compromised when adjusting size

Issue with blurry images after resizing. The problem is noticeable in the three main images located under the Header section. To preview the blog, click on this link: Click Here Your assistance in solving this issue would be greatly appreciated. Thank yo ...

Discover the shortest path on Google Maps and customize your route using a specific address or latitude/longitude coordinates. Choose between the default current location marker or customize one to fit your needs

Currently facing an issue with Google Distance Map. Our situation involves multiple locations, and I am trying to generate a map from my current location to the nearest address among the given multiple addresses. The map creation is already set up and fu ...

What is the correct way to access an element with spaces in handlebars while working with node.js?

I have an object containing values with spaces in strings. For example: object = { "group of people": [ { (...) } ], "another group of people": [ { (...) } ] } Now, I want to use this object with the handlebars helper block in my view ( ...

Concealing a button within a specific interface

I am currently facing an issue with a data table that includes two control buttons: edit and save. My problem lies in hiding the save button on the initial preview. Basically, what I want to achieve is displaying only the Edit button on the first page. Wh ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Having trouble loading popper.js using Laravel mix and webpack

I have been working on my project with Bootstrap 4 beta and Laravel 5.4, using npm and Laravel mix to load my JavaScript dependencies. Everything was going smoothly until I encountered an error while trying to use Bootstrap JavaScript methods. The error me ...

How can I implement a "remember me" feature on login using Firebase in the routes.js file?

I am currently developing an ionic app that utilizes Firebase Google authentication. Despite having a working login logic, I am facing issues with the routing as it crashes the app. Strangely, there are no errors displayed in the console, the app simply go ...

AngularJS is throwing a RangeError, indicating that the time value is invalid when calling Date.toISOString

For my project, I need to display the date picker in jQuery (angular-jquery-datepicker) with the date formatted correctly for the user's timezone. I can successfully show dates in both USA and EU formats. When the user sets these dates, I have to save ...

To combine arrays A and B within a React useState object, simply pass them as arguments when initializing the state

Currently, I am working on integrating infinite scroll functionality in React, where I need to fetch data from a backend API for loading content on the next page. The challenge I'm facing is that my state is set as an object using useState, and I need ...