Zyx Sun
Zyx Sun

Reputation: 439

ng-click on addClass event will only fire on the second click of the button

I have a bootstrap alert that looks like this

<div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-if="itemExistsAlert">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <p>{{alertMessage}}</p>
</div>

and I will add/remove class dynamically using jquery/angular (the code below will only run when the user doesn't put any value in the input text and will click the addItem button)

addItem button:

<button ng-click="addItem()" class="btn btn-success" type="button">Add</button>

function that will handle the ng-click

$scope.addItem = function() {
  var errorAlert = angular.element(document.querySelector('#errorAlert')); 
  if (!$scope.pollItem) {
        errorAlert.addClass('alert-info');

        $scope.alertMessage = "Item cannot be null";
        $scope.itemExistsAlert = true;
        $timeout(function() {
            $scope.itemExistsAlert = false;
        }, 2000)
        return;
    }
}

The code is working well BUT the addClass event will only fire after I will click the button TWICE. I mean the alert will fadeIn/fadeOut perfectly but only the class is not added in the first click but on the second click of the button the class will be added to the alert.

Thank you for anyone that can help me.

Upvotes: 2

Views: 743

Answers (1)

Gal Grazia
Gal Grazia

Reputation: 477

It's because ng-if removes the element from the dom and you are trying to add a class to a non exisiting element (yet) in the function

Either use ng-show instead of ng-if:

<div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-show="itemExistsAlert">
<button type="button" class="close" data-dismiss="alert">&times;</button>
<p>{{alertMessage}}</p>
</div>

or you can use ng-class:

<div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-class="{'alert-info':itemExistsAlert}"  ng-if="itemExistsAlert">
<button type="button" class="close" data-dismiss="alert">&times;</button>
<p>{{alertMessage}}</p>
</div>

Upvotes: 2

Related Questions