0

I have a custom directive which does validation, based on the directive attribute value.

e.g.: <input type="text" ng-my-validate="onlyletters" />

I want to change the onlyletters value to onlynumbers on the fly and want to the directive change it's validation behaviour because of that.

How can I achieve this?

3
  • Why not HTML5's pattern or AngularJS's ng-pattern? Commented Jan 8, 2016 at 16:46
  • onlyletters is just an example. My real validation rules are Brazilian document numbers. Commented Jan 8, 2016 at 16:47
  • How is your directive set up? I don't see why this wouldn't be very easy to do. Commented Jan 8, 2016 at 16:54

1 Answer 1

2

You should be using attribute $observers.

UPDATE: @MatthewGreen is correct. I overlooked the fact that you are not using a interpolated value. In this case consider using a $watcher with plain jQuery attribute reading:

angular.module('mod', [])
  .directive('ngMyValidate', function() {
    return {
      link: function(scope, elm, attr) {
        scope.$watch(function() {
          return elm.attr('ng-my-validate');
        }, function(value) {
          console.log('attribute changed:', value);
        });
      }
    };
 });

Thanks @MatthewGreen!

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

2 Comments

The attribute doesn't appear to use interpolation though so I'm not sure how this would help them.
Good catch @MatthewGreen. Updated my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.