3

I am creating a login page using angular and typescript. When the submit button is clicked, I would like the login function in the controller to fire, but if the form is invalid then it just returns.

This is my first time using typescript, so every time I try to put in the if statement to check if the form is invalid it throws the error Cannot read property '$invalid' of undefined.

Here is the html:

<form class="login-form" name="loginForm" ng-submit="vm.login()" novalidate>
     <input type="email" name="email" placeholder="Email" required ng-model="vm.email" ng-class="{true: 'input-error'}[submitted && loginForm.email.$invalid]"/>
     <input type="password" name="password" placeholder="Password" required ng-model="vm.password" ng-class="{true: 'input-error'}[submitted && loginForm.password.$invalid]"/>
     <input type="submit" id="submit" ng-click="submitted=true"/>
</form>

And here is the compiled javascript:

var LoginModule;
(function (LoginModule) {
    var LoginController = (function () {
        function LoginController() {
        }
        LoginController.prototype.login = function () {
            if(this.loginForm.$invalid) {
                return;
            }
            console.log("Login was clicked, email is " + this.email + " and password is " + this.password);
        };
        return LoginController;
    })();
    LoginModule.LoginController = LoginController;
})(LoginModule || (LoginModule = {}));
angular.module('loginModule', []).controller('LoginController', LoginModule.LoginController);

It looks like the common issue with this was that people were not specifying the form name, but that is not the case here. Does anyone know why I could be getting this error?

2 Answers 2

3

You need the controller alias in the form name

<form  name="vm.loginForm" ng-submit="vm.login()" novalidate>
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, just started using the controllerAs syntax as well. Thanks!
0

While @charlietfl's answer is correct for the OP's question, this error can also be thrown if you've missed the ng-model property on an input control and are using the ui.bootstrap.showErrors $scope.$broadcast('show-errors-check-validity') method.

As per the documentation (my emphasis):

.. an input control that has the ngModel directive holds an instance of NgModelController. Such a control instance can be published as a property of the form instance using the name attribute on the input control. The name attribute specifies the name of the property on the form instance.

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.