1

I am able to validate my form element 'name'd 'username'.

ng-class="{ 'has-error': form.username.$dirty && form.username.$invalid }"

But I cannot get this info inside a controller. Is this possible?

I want to do something like this:

mycontroller.controller('mycontroller', function ($scope){

    $scope.isusernameinvalid = $scope.form.username.$dirty && $scope.form.username.$invalid;
});

And use the isusernameinvalid (true/false) to toggle class

ng-class="{ 'has-error': isusernameinvalid }"

I know "form" is not a $scope variable, and hence inaccessible.

How do i access the validation state/class info over here?

1 Answer 1

1

If you declare the form like this

<form name="formName"></form>

you should be able to access it in the controller via $scope.formName. However as always in angular you have to be careful about looking in the correct scope, so maybe set ng-controller="mycontroller" on the form tag or on some tag that contains the form tag if not done already.

It could also be that when the $scope.isusernameinvalid = $scope.form.username.$dirty && $scope.form.username.$invalid; code runs the form hasn't been initialized in the scope yet, so accessing it returns undefined. Declaring isuernameinvalid as a function instead should get around that:

$scope.isUsernameInvalid = function() {
    return $scope.form.username.$dirty && $scope.form.username.$invalid;
}

And then call it as a function in your ng-class directive.

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

Comments

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.