如果我通过ng-class向元素添加一个类并尝试通过angular-element获得相同类的存在,则它总是返回false。
请告诉我以下代码的错误,
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'));
} });
答案 0 :(得分:1)
问题是你正在检查回调函数中的.hasClass
,这是在角瞄digest cycle开始之前执行的。
目前: 1.按下按钮 - 2.执行$ scope.add - 3.检查类别 - 4. Angulars摘要周期更改类
要解决此设置$ timeout,会将console.log
移动到堆栈底部。
<强> 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);
}
}]);