From the answer to a similar question:
The error you make is what you expect from the jQuery trigger method. If you look at the code, you will see that it actually executes the event handlers processed by jQuery and not DOM Level 3. Since it only executes jQuery, you will not raise the change event that you need to activate the value of the text field property.
Instead, you can update the input value and trigger a change or input event:
input.val('x').trigger('input');
However, when doing this inside the controller in a real application (as opposed to the unit test environment) you need to exit the $ digest cycle or get the $apply already in progress error.
You can do this, for example, using setTimeout :
$scope.trigger = function() { setTimeout(function() { $('input').val('x').trigger('input'); }); };
You also need to make sure that you load jQuery before AngularJS. If you do not, Angular will use jqLite. jqLite uses addEventHandler to register event handlers, and handlers registered this way are not triggered by the jQuery trigger function.
Demo of the updated code: http://plnkr.co/edit/u3ZWXWLvOjbKWlY8JEM5?p=preview
In unit testing:
it('should work', function() { var element = $compile('<form name="form"><edit ng-model="name"></edit></form>')($scope); $rootScope.$digest(); var scope = element.scope(), form = scope.form, input = element.find('input'); expect(form.$dirty).toBe(false); input.val('x').trigger('input'); expect(form.$dirty).toBe(true); });
Unit test demo: http://plnkr.co/edit/Emc3dIlDaxXyE9U6dEG6?p=preview
source share