6

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?

3
  • the model value is being watched, set user.siteId = 2 instead Commented Apr 17, 2019 at 7:56
  • @svarog how do I set a model value from JS? user.siteID = 2; does not work because user is not defined. Commented Apr 17, 2019 at 8:01
  • you do it in the controller, you define and object user and add a property siteId with the value 2, e.g. $scope.user = {}; $scope.user.siteID = 2; Commented Apr 17, 2019 at 8:13

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the help, I got it working like this: angular.element(document.getElementsByTagName('BODY')[0]).scope().user.setSelectedSite(2)
@user2976138 I'm glad I was able to help.
.scope() is only available in debug mode

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.