1

I have a form element with an ng-change handler. I want to programmatically trigger the handler, but without direct inspection of scope. I want to do this because I'm writing a Chrome extension so I can't easily access '$scope' to get the handler.

I have tried the obvious choice of

$(element).triggerHandler('change')

but that doesn't seem to work. See example here: https://plnkr.co/edit/iaz7trxVT09XWBktGhE9?p=preview (in this example I'm logging some lines to console when the change handler runs, but clicking the button doesn't log those lines).

I tried a few other methods found in various threads here, such as trigger() or manual construction of event and fire with dispatchEvent but to no avail. I don't quite understand why the event handler isn't triggering. Can anyone help?

5
  • Unlike other ng-<event> directives, ng-change is not bound to the underlying element's change event. It is bound to ng-model's $viewChangeListeners, so there is no way to invoke it manually, unless you have access to tge scope. Why are you using ng-change? Would ng-input work instead? Commented Jan 17, 2017 at 7:49
  • Thanks. That explains a lot! I can't control the page as I'm writing a Chrome extension to fill in forms, but this explains why my code wasn't working! Commented Jan 17, 2017 at 8:04
  • actually you can access $scope from the outside world by using scope = angular.element($(element)).scope(), so there is no need to trigger change Commented Jan 17, 2017 at 8:09
  • I don't even have access to 'angular' inside a Chrome extension. I suppose I can load angular JS file in and see if that works (it should - I can also just extract the code that runs angular.element(element).scope() as it's pure JS and the data should be stored in DOM anyway). Commented Jan 17, 2017 at 21:21
  • @user3759055 have you found any solution???? Commented Oct 2, 2020 at 9:07

1 Answer 1

1

Well, apparently (according to docs), the model change will not be triggered when the value is not changed. An ugly (yet effective) workaround would be to actually change the value briefly:

var v = $('#testField1').val();
$('#testField1').val(0)
$('#testField1').triggerHandler('change');
$('#testField1').val(v)
$('#testField1').triggerHandler('change');

Of course this will trigger the event twice, if this is a problem you could for example use a known "magic value" (e.g. min negative integer) and ignore it.

Alternatively, I'm afraid there is no simple solution: you might need to access the scope / controller to invoke the function you want directly or meddle with angular's event handling.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.