sayam
sayam

Reputation: 163

Display an alert after submitting a form using angularjs

I'm using AngularJS for a login form, and I'm making an API call to the server with username/password and display an alert.

login.jade

// form
input(type="submit",ng-click="submit()")
div.alert(ng-show="showAlert",class="{{alert}}",ng-animate="{show: 'alert-show', hide: 'alert-hide'}")
button(ng-click="showAlert = !showAlert") fadeIn

controller.js

$scope.submit = function () {
  if ($scope.username != undefined && $scope.password != undefined) {
    $http({
      method: 'POST',
      data: {
        username: $scope.username,
        password: $scope.password
      },
      url: 'api/login'
    }).
    success(function (data, status, headers, config) {
      if (data.auth) {
        $scope.alert = data.alert;
      } else {
        $scope.alert = data.alert;
      }
    }).
    error(function (data, status, headers, config) {
      // something else
    });
    $scope.showAlert = true;
  }
}

data.alert is the class of the alert (alert-success, alert-warning), but it instantly shows the alert, without fading. If I remove the $scope.alert = data.alert, everything works fine. I was thinking about having 2/3 div.alert, and having different scopes ($scope.alert1, $scope.alert2) but I'm sure there is a better way.

Moreover, on the initial load, the div.alert is displayed then faded. I could set the alert on display: none when loading, but I was looking for a 'cleaner' way.

English is not my native language, so I might have made mistakes, my apologies. Thanks.

Upvotes: 0

Views: 4132

Answers (1)

Zajn
Zajn

Reputation: 4088

$scope.showAlert = true is outside of your success and error callbacks. So you're essentially setting showAlert to true as soon as you set up your call to $http.

Remember that the $http service returns a promise and the callbacks (success and error in this case) are not invoked immediately. They'll only be invoked once the server responds. Try setting $scope.showAlert = true inside your success function and see if that is more like what you were expecting.

Upvotes: 2

Related Questions