Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger ng-change from jquery?

Tags:

angularjs

I have a select tag as follows:

<select ng-change="doSomething()" ng-model="myModel"> </select>

and I'm using a jQueryUI control for it (combobox), the event "change" triggered from jQuery doesn't trigger doSomething().

Do you know how to trigger ng-change from outside angular?

like image 860
htellez Avatar asked Jun 20 '14 15:06

htellez


People also ask

What is trigger method in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

What is Ng Onchange?

The ng-change event is triggered at every change in the value. It will not wait until all changes are made, or when the input field loses focus. The ng-change event is only triggered if there is a actual change in the input value, and not if the change was made from a JavaScript.


2 Answers

The question is not how to run some code, but rather how to trigger the change event. I found an angular-friendly way to do this. I have a jQuery UI slider that changes the value of another input which has the ng-change on it. The secret is that once you turn it into an angular.element you now have access to a method called triggerHandler. From what I've seen, using this would not be considered bad practice:

angular.element(document.getElementById('test')).triggerHandler('change');

tymeJV's answer did angular.element("#test") directly without using jQuery, but I got a console error and broken functionality that way. This version works without any dependencies.

like image 51
claywhipkey Avatar answered Oct 17 '22 06:10

claywhipkey


Ugh - this is terrible practice - but you can use angular.element and get the scope from an element that resides within the target controller.

Example:

<div ng-controller="myApp">
    <span id="test"></span>
</div>

Javascript:

var scope = angular.element("#test").scope();
scope.doSomething();

Your scope variable now has access to all the methods defined on the myApp controller.

like image 32
tymeJV Avatar answered Oct 17 '22 07:10

tymeJV