user2976138
user2976138

Reputation: 85

Triggering ng-change Event Programmatically From Javascript

I am trying to trigger an ng-change event programmatically from some javascript.

This is the element I am trying to trigger the ng-change event for

<select ng-model="user.siteId" name="siteSelect" ng-change="user.setSelectedSite(user.siteId)" class="ng-pristine ng-untouched ng-valid ng-empty">
    <option value="" selected="selected">Please Select A Site</option>
    <option id="siteOpts" value="1" ng-repeat="site in user.sites  | orderBy:'siteName'" class="ng-binding ng-scope">Site1</option>
    <option id="siteOpts" value="2" ng-repeat="site in user.sites  | orderBy:'siteName'" class="ng-binding ng-scope">Site2</option>#
    <option id="siteOpts" value="3" ng-repeat="site in user.sites  | orderBy:'siteName'" class="ng-binding ng-scope">Site3</option>
</select>

I know I can select a value using this code

document.querySelector('.ng-pristine.ng-untouched.ng-valid.ng-empty').value = 2;

However this does not result in the ng-change event firing.

How can I select a value and ensure the ng-change event is fired?

Upvotes: 6

Views: 3934

Answers (1)

NTP
NTP

Reputation: 4448

According to the documentation

The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

It will not be evaluated:

  • if the value returned from the $parsers transformation pipeline has not changed
  • if the input has continued to be invalid since the model will stay null
  • if the model is changed programmatically and not by a change to the input value

Note, this directive requires ngModel to be present.

What you can do is to manually call your function from your controller

user.setSelectedSite(user.siteId)

or use $scope.$watch.

Upvotes: 3

Related Questions