SalmanShariati
SalmanShariati

Reputation: 3893

how to programatically set ng-pristine to ng-dirty using jQuery?

I am trying to the set username in an input. It fills the input and runs the keypress event, but it does not change ng-pristine to ng-dirty. Any idea?

My code:

var username = ["u", "s", "e", "r"];

$("#username").keypress(function(event) {
  var key = event.keyCode || event.which;
  $('#username').val($('#username').val() + String.fromCharCode(key));
});

for (var i=0;i< username.length;i++){
  var c = username[i];
  $('#username').trigger(jQuery.Event('keypress', {which: c.charCodeAt(0)}));
};

Upvotes: 1

Views: 2413

Answers (2)

mohamedrias
mohamedrias

Reputation: 18566

As you're working out of angular scope, you need to trigger $scope.$apply() manually to trigger the change. Also you must set the flag setDirty() manually.

Get the reference of the controller scope you're working on currently.

var scope = angular.element(document.querySelector("controllerSelector")).scope();

Now inside your keypress event, trigger the digest cycle.

var username = ["u", "s", "e", "r"];

$("#username").keypress(function(event) {
    var key = event.keyCode || event.which;
    $('#username').val($('#username').val() + String.fromCharCode(key));
    scope.$apply();
});

for (var i=0;i< username.length;i++){
    var c = username[i];
    $('#username').trigger(jQuery.Event('keypress', {which: c.charCodeAt(0)}));
    scope.$apply();
};

This must fix your issue mostly. If not, you may need to trigger the setDirty() manually. In scope point to the form and set the dirty flag.

scope.formName.$setDirty();

Upvotes: 2

Steve
Steve

Reputation: 276

Why are you mixing jquery and angular? You should never do that. If you want to listen for change events or clicks. Attaches ng-click or ng-change to the dom element or set up a $watch in the controller to listen for any changes to the model. It's poor practice to mix jquery selectors and angular in the same project. Angular has all the features you are looking to get out of jquery.

Upvotes: -1

Related Questions