0

if i add a class to an element through ng-class and try to get the existence of the same class through angular-element, its always returns false.

Please let me know whats wrong with the below code,

html:

<body ng-app="myApp">
<div ng-controller="myController">
<input type="text" ng-class="{'red':required == true}"/>
<button ng-click="add()">click</button>
</div>
</body>

css:

.red {border: 1px solid #ff0000;}

javascript:

var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope){

var elem = angular.element(document.querySelector('input'));
$scope.required = false;
$scope.add = function(){
$scope.required = true;
console.log(elem.hasClass('red'));
}    });
user1153484
  • 197
  • 3
  • 13

1 Answers1

1

The issue is that you are checking .hasClass inside the callback function, this is executed before angulars digest cycle starts.

So currently: 1. Button pressed - 2. $scope.add executed - 3. Class is checked - 4. Angulars digest cycle changes class

To solve this setup a $timeout which will move your console.log to the bottom of the stack.

Working fiddle here

var myApp = angular.module('myApp',[]);
myApp.controller("myController", ['$scope', '$timeout', function($scope, $timeout){

    var elem = angular.element(document.querySelector('input'));

    $scope.required = false;
    $scope.add = function(){
        $scope.required = true;
        $timeout(function(){
            console.log(elem, elem.hasClass('red'));
        }, 0);
    }

}]);
Simon Staton
  • 4,345
  • 4
  • 27
  • 49