StevieB StevieB - 1 year ago 498
AngularJS Question

Angular : Dropdowns, prevent ng-selected to fire ng-change

I am populating dropdowns in a forloop and wish to set the default value for each dropdown based on an expression. This seems to be working but my problem is when I set the default value via ng-selected it also fires change event which is not ideal.

I would like the change event only to be fired if the dropdown is actually changed.

<div layout="row" ng-if="layer.Styles && layer.Styles.length > 1">
<md-input-container class="md-icon-float md-block layer-style">
<md-select ng-change="vm.changeLayerStyle(layer,selectedStyle)" ng-model="selectedStyle" ng-model-options="{trackBy: '$value.Name'}" aria-label="Change Layer Style">
<md-option ng-repeat="style in layer.Styles" ng-value="style" ng-selected="style.IsDefault == true">

Using angular material for the dropdown

Answer Source

Repeating over option elements have a history of giving people problems. Normally i'd tell you to use ng-options on the select instead, but since you specifically need to use some material components, that is not an option.

I know it's not the prettiest solution, but you could solve the problem by keeping a copy of the last value and compare it to the current once the change event is fired. If that value has not changed, then ignore the event. This might need some extra tweaking since setting the layer. Styles will probably just trigger a lot of updates.

Since you didn't give us a plunker to play with, i can only suggest you play around with ng-model-options (which you are already using to control track-by) the updateOn property and setting it to something that won't be triggered by you setting the selected property. The value blur comes to mind here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download