V
V
Vassa2014-06-02 07:24:23
Angular
Vassa, 2014-06-02 07:24:23

Why doesn't watch in a directive work when entering a value?

Actually, there is an ng-email-valid directive that validates email and, depending on the result, shows an error, but in this case, watch does not work at all when you type. There is a similar directive, I only have the name field there and everything works, but here I don’t see any errors and watch doesn’t work :(

<input class="d-form__input-text" ng-model="email" ng-required="true" ng-focus="focusHandler($event)" ng-blur="blurHandler($event)" name="email" type="email">
<div class="d-form__error" ng-email-valid="orderingForm.email">Пожалуйста введите корректный email</div>

.directive('ngEmailValid', ['$parse', function($parse) {
    return function(scope, element, attr) {
        var EMAIL_REGEXP = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + "",
            model = scope.$eval(attr['ngEmailValid']);

        scope.$watch(model.$name, function() {
            model.$invalid && model.$dirty ? element.show() : element.hide();
        });
    }
}])

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
Sergey, 2014-06-02
@Mr_Pukin

Use isolated scopes:

directive('ngIsInputValid', function () {
    return {
        scope: {
             input: '=ngIsInputValid'
        },
        link: function (scope, el, attr) {
             scope.$watch('input.$invalid', function (invalid) {
                   if (invalid && scope.input.$dirty) {
                         el.show();
                   }
                   el.hide();
             })
        }
    };
});

ps any validation should take place on inputs and be done through ngModelController.

M
Mikhail Osher, 2014-06-02
@miraage

1) ngRequired should only be used when passing expression . In this case, the normal required attribute is sufficient .
2) Your directive is not needed in this case. It is enough to write something like this code:

<!-- предположим, что где-то выше есть <form name="form" ...> -->
<div class="d-form__error" data-ng-if="form.email.$invalid">
    Пожалуйста введите корректный email
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question