Saras Arya
Saras Arya

Reputation: 3112

How to show error messages in AngularJS?

I have services and controllers written in AngularJS, in which I am sending a post request to Node.js Application and using send status and code to send a error message like Username already exists orWrong email and password but I am not getting How to show these errors in frontend HTML. Like after submit is pressed probably. How would you go about it?

$http.post('/register', registerUser).then(function(response){
                console.log(response.data);
}

How will I show response .data in the HTML. I read about $error in angular but I don't think it will work in my case as mine is a custom error.

Thanks

Upvotes: 2

Views: 35076

Answers (3)

I think that is better like this:

Message error

Upvotes: 0

Daniel Kuta
Daniel Kuta

Reputation: 1634

You can use alert with Bootstrap:

<div ng-show="hasError">
<alert ng-repeat="error in errors track by $index" type="danger"  close="closeAlert($index)">{{error}}</alert>
</div>

in controller:

$scope.errors = [];
$scope.hasError = false;
$scope.closeAlert = function (index) {
    $scope.errors.splice(index, 1);
}

$http.post('/register', registerUser).then(function(response){
switch(response.data) {
    case 'error1':
        $scope.hasError = true;
        $scope.errors.push('error1');
        break;
    case 'error2':
        $scope.hasError = true;
        $scope.errors.push('error2');
        break;
    default:
        $scope.hasError = true;
        $scope.errors.push("I don't know whats going on");
    }
 }
};

You can use it everywhere.

Upvotes: 4

KyleK
KyleK

Reputation: 5131

Your HTML should be something like:

<div ng-if="errorMessage">{{ errorMessage }}</div>

Then you can modify $scope.errorMessage to display it:

$http.post('/register', registerUser).then(function(response){
    switch(response.data) {
        case 'loginExists':
            $scope.errorMessage = 'Username already exists';
            break;
        case 'loginError':
            $scope.errorMessage = 'Wrong email and password';
            break;
        default:
            $scope.errorMessage = false;
    }
}

Upvotes: 14

Related Questions