0

i like to watch the validity of an input element inside a directive. My controller is always undefined. How can i watch properties like $valid, $invalid on a input element ?

app.directive("myElement", function()
{
    return {
        restrict: "A",
        templateUrl: "./Templates/tooltip.html",
        scope: {
        },
        compile: function (element, attrs) {
            return {
                pre: function preLink(scope, element, attrs, controller) {
                },
                post: function postLink(scope, element, attrs, controller) {
                   scope.$watch(function(){return controller.$invalid;},function(newVal,oldVal){
                   });
                }
             }
         }
}
1

1 Answer 1

1

For the controller argument of the (pre-, post-, -) link function to work you have to require one or more controllers:

return {
    require: "ngModel",
    ...
};

Or more:

return {
    require: ["ngModel", "foo", "bar"],
    ...
};

This will not solve your problem though; You need to define a controller in the directive and make sure that the root element of the template is a named form. So you can do:

Template:

<form name="theForm">
    <input name="myInput" ng-model="foo.name" />
</form>

Directive:

return {
    controller: function($scope) {
        $scope.watch("theForm.myInput.$valid", function(isValid) {
            ...
        });
    },
    ...
};
Sign up to request clarification or add additional context in comments.

4 Comments

i like to avoid to use a form. need a solution without it.
Try adding the { require: "ngModel" } part of the answer to your code, but make sure the template is the <input>, or it does not work. Keep the same code in the link function.
how can i make sure the template is <input>... just leave templateUrl away ?
If there is no template/templateUrl, then make sure you will be using your directive only on elements with ng-model. If not, Angular will throw an error (required controller not found), so it is safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.