Reputation: 4892
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?
Upvotes: 1
Views: 2641
Reputation: 660
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.
Upvotes: 1