Chris Hammond
Chris Hammond

Reputation: 2186

Angular: Control that fired ng-change

I have an Angular form that has several input boxes that I want to validate, using a generic JS function but need to know the control that fired the event so certain rules can be applied.

(Simplified code)

<input ng-model="Field1" ..... ng-change="validateMe()" />
.
.
<input ng-model="FieldX" ..... ng-change="validateMe()" />

$scope.validateMe = function() {
   // get the text of the control that fired the event

   // do the validation 

   // update something else if valid value given

}

I know that ng-click has the $event, but how can I do it from an ng-change

Upvotes: 1

Views: 640

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You could have you own custom directive that will call your controller method on custom change event.

Markup

<input ng-model="Field1" my-custom-change change-method="validateMe(event)">

<input ng-model="FieldX" my-custom-change change-method="validateMe(event)">

Directive

app.directive('myCustomChangeEvent', function(){
  return {
    scope: {
      changeMethod = '&'
    },
    link: function(scope, element, attrs){
      element.on('change', function(event){
        scope.changeMethod({event: event});
        scope.$apply();
      });
    }
  }
})

Upvotes: 1

sma
sma

Reputation: 9597

Don't do this in the ng-change. I would do this validation with an attribute directive instead. This way you have full access to the element in question and can apply custom validation rules based on that.

    return {
        restrict : 'A',
        require : 'ngModel',
        link: function (scope, elm, attrs, ctrl) {

            ngModel.$parsers.push(function (value) {
                if (isElementInQuestion(elm) {
                    ngModel.$setValidity('myCustomValidMessage', scope.validateField(value));
                }
                return value;
            });
        }
    };

Upvotes: 0

Related Questions