Suamere Suamere - 1 year ago 60
AngularJS Question

Directive ngChange fires as many times as combobox options

I have a Countries dropdown, nothin' fancy. My only oddball requirement is that I want to be able to pass in an OnChange function from my controller so the Directive can run it. Here is a Plunker

In the Plunker, I have this basic template:

<label for="countryDirective">Country</label>
<select id="countryDirective" ng-model="country" ng-Change="countryChanged()" ng-options="obj.value as for obj in countries">
<option value="">Choose Your Country</option>

The only difference between the On-Page HTML and the Directive Template is that I added ng-Change onto the On-Page HTML.

One point of note is in my Directive, I am using
require: '^ngChange'

I don't know why it isn't documented very well, but it works wonders and gets around all of the problems posed by other questions relating to change event firing before the scope is updated and other change issues.

However, the price for this elegance is that my countryChanged() function is being fired x times, where x is the number of items in the drop-down. I assume because items are being observed one at a time and so changes keep happening?

So my main question is: How do I keep this elegance, but make the ng-Change only fire once per change?

Edit: Turns out switching to select ngOptions instead of option ngRepeat fixes my issue with them not sync'ing, but not the main issue of why my ngChange is firing x times in the Directive.

Answer Source

I guess the issue was setValue: '=ngChange'

I changed it to setValue: '&ngChange' and added ng-change="setValue()" to <select/>

Now its triggering only once when you change it (verify console log).

I have updated plunker

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