0

Where is it best to handle both error handling, and error display? E.g.

I have a controller:

angular.module('app')
    .controller('MyController', function ($scope) {
        $scope.form = {
            username: ''
        };

        $scope.login = function () {
            doSomething($scope.form.username);
        };
    });

And a view bound to the controller:

<div ng-controller="MyController">
    <input ng-model="username.form" />
    <button ng-click="login()">Submit</button>
</div>

If $scope.form.username is blank, this is an error; where is it best to handle this? In the controller, e.g.:

if ($scope.form.username == '') {
    // do something here
}

Or just pass the value to doSomething(...) and let that function handle a blank value?

Secondly, what's the best method to update the element (say, to highlight the input red or to show a small message underneath) to indicate that an error has occured?

1 Answer 1

1

You should read the article about the angular form validation (http://www.ng-newsletter.com/posts/validations.html). It provides everything you need to set a good form validation.

After this, you can implement a check on Submit to prevent submitting the form if there are validation errors :

    $scope.signupForm = function() {
        if ($scope.signup_form.$valid) {
          // Submit as normal
        } else {
          //no submit, notify the user 
        }
    ...}

And for the error messages, as they are rendered in the view, you can manage them directly in your directive like :

<input type="text" placeholder="Name" name="name" ng-model="signup.name"       ng-minlength=3  ng-maxlength=20 required />
       <div class="error-container" ng-show="signup_form.name.$dirty && signup_form.name.$invalid && signup_form.submitted">
        <small class="error" ng-show="signup_form.name.$error.required">
            Your name is required.
        </small>
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.