user1694873 user1694873 - 5 months ago 102
AngularJS Question

Prevent md-select dropdown opening under certain condition when clicked

I have an with an and I am trying to stop the md-select from opening under a certain condition and instead show a warning dialog.

I am able to disable the md-select with the following

ng-disabled="controller.unsavedChangesMade"


but I would prefer to avoid this and instead allow the user to click on the dropdown with the dialog showing up, and without the md-select list of items opening up. If I remove the ng-disabled, the dialog and dropdown list of items shows 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 looked into using

$event.stoppropagation()


but I was unable to get this to stop the dropdown list opening.

I am not sure if this is possible but any help would be greatly appreciated,

Thanks

Answer

You can use event.stoppropagation() 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 }; });
      });
})();