Stop md-select dropdown from opening when clicked in specific scenario

I currently have a situation where I want to prevent the md-select from opening under a specific condition and instead display a warning dialog.

One way I can achieve this is by disabling the md-select using the following code:

ng-disabled="controller.unsavedChangesMade"

However, I would prefer a solution that allows the user to click on the dropdown, triggering the warning dialog without the md-select list appearing. Removing ng-disabled causes both the dialog and dropdown list to show up.

<md-input-container>
    <label>Select Item</label>
    <md-select ng-disabled="controller.unsavedChangesMade" ng-model = "selectedItem" ng-click="controller.handleItemChange(selectedItem.name, $event)" aria-label="Selected Item">
        <md-option ng-repeat = "(index,item) in controller.items" ng-value = "item"
                   ng-click = "controller.getItemByCategory(item.name)">
            {{item.name}}
        </md-option>
    </md-select>
</md-input-container>

I have explored using

$event.stoppropagation() 

but it did not prevent the dropdown list from opening.

If you have any insights on how to achieve this, I would greatly appreciate your help. Thank you.

Best regards

Answer №1

To prevent event propagation, you can utilize event.stoppropagation() in conjunction with the md-on-open attribute - CodePen

<div ng-controller="AppCtrl as ctrl" class="md-padding selectdemoBasicUsage" ng-cloak="" ng-app="MyApp">
  <div>
    <div layout="row">
      <md-input-container>
        <label>State</label>
        <md-select ng-model="ctrl.userState" md-on-open="ctrl.test($event)">
            <md-option ng-repeat="state in ctrl.states" value="{{state.abbrev}}">
              {{state.abbrev}}
            </md-option>
          </md-select>
      </md-input-container>
    </div>
    <md-button ng-click="ctrl.toggle()">Toggle</md-button>
  </div>
</div>

JS

(function () {
  'use strict';
  angular
      .module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
      .controller('AppCtrl', function() {
        this.unsavedChangesMade = false;

        this.toggle = function () {
          this.unsavedChangesMade = !this.unsavedChangesMade;
        };

        this.test = function (event) {
          if (this.unsavedChangesMade) {
            event.stoppropagation();            
          }
        };

        this.userState = '';
        this.states = ('AL AK AZ AR').split(' ').map(function (state) { return { abbrev: state }; });
      });
})();

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

JavaScript parsing error occurred

Encountering a parsing error in my JavaScript code when deploying Firebase functions. The error mentions an unexpected token, indicating there might be a character out of place. I've been stuck on this issue for weeks now. Any assistance would be grea ...

Is it possible to halt the execution of a code or skip the remainder of it if a specific condition is met using jQuery?

Is it possible to prevent a code from completing or skipping the remaining parts based on a specific condition? For example, var stopCode = false; if (stopCode === true) break; .... .... blah blah blah the remaining part of the code .... ... Can this b ...

Showcasing a Collection of Dropdown Options for All Angular Material Icons in Angular Versions 2 and Above

I'm currently developing an Angular 10 application that utilizes Angular Material Icons. I am in search of a method to dynamically showcase a dropdown menu containing all the available Material Icons. My attempt to programmatically retrieve the icon ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

What is the most effective method for inputting a date/time into a Django view?

Looking to create a feature where users can see what events are happening at a specific time. What is the most efficient method to implement this request? For example, if I want to display all current events, should I submit a post request to /events/2009 ...

The Bootstrap 4 modal appears to be failing to load properly, as it is only

Trying to trigger a Bootstrap modal with a button click. Currently, there is one functioning modal on the page that works fine. However, when attempting to load another modal on a button click, only a faded screen appears. <button class="btn btn-green ...

Sending an image dynamically as a prop to a child component

Within my parent component, I retrieve an object from an API which I later enhance with an image as a key/value pair. Subsequently, I pass this modified object to a child component for rendering. In order to accomplish this, I referred to the following pos ...

Exploring how to use mongoose queries within express routes

Having issues testing my routes with mongoose queries. I keep receiving this error: AssertionError: expected undefined to equal true Below is the structure of my test. Right now, I just want to verify that it calls res.json. The route retrieves all reco ...

Alter the background image of a DIV based on the selected menu item

I am working on a project that involves a div element with the class "jumbotron" which currently has a background image applied to it. Additionally, I have a menu consisting of 6 items that I would like to interact with. My goal is to dynamically change ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

React Tetris game always returns false in its function

Within my react project, I am working with a 2D array containing numbers. I have implemented a function called collisionCheck that iterates through the array to check for specific values. My goal is for this function to return true and exit when it encou ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...

Modify a website link using Javascript by detecting two separate button clicks

I am seeking a way to dynamically change the src attribute of different images on a house depending on which button has been clicked. There are two groups of buttons: The types of house parts, such as windows, doors, garage, soffits, and gutters. The col ...

"Troubleshooting ways to resolve babel-eslint import/export issues without the need for a configuration

Upon running npm start, I encountered the following error message: Parsing error: 'import' and 'export' may only appear at the top level After investigating this issue, suggestions included updating the eslint configuration file with ...

javascript image alert

I want to upgrade a basic javascript alert to make it look more visually appealing. Currently, the alert is generated using if(isset($_GET['return'])) { // get a random item $sql = "SELECT * FROM pp_undergroundItems AS u LEFT JO ...

Inquiry into AngularJS data binding

Just dipping my toes into the world of Angular today. Found a tutorial at Angular JS in 30 mins This little project involves setting up basic databinding in Angular. The code features an input box that updates with whatever is typed next to it. As someone ...

How to eliminate the comma from the final element in a JavaScript Vue.js array?

I'm looking to remove the comma from the last element in Vue, but I'm unsure how to do so since the index of the last element is unknown. <td v-if="category.sub_category.length > 0"> <template v-for=&q ...

Utilizing Angular Filter to compare the date in a JSON file with the current system date

<p id="appt_time" ng-if="x.dateTime | date: MM/dd/yyyy == {{todaysDate}}">DISPLAY IF TRUE{{todaysDate}} </p> Plunkr:https://plnkr.co/edit/r2qtcU3vaYIq04c5TVKG?p=preview x.dateTime | date: MM/dd/yyyy retrieves a date and time which results in ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...