【问题标题】:angular.element not works when class is added through ng-class通过 ng-class 添加类时,angular.element 不起作用
【发布时间】:2015-03-24 09:45:02
【问题描述】:

如果我通过 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'));
}    });

【问题讨论】:

    标签: javascript angularjs jqlite


    【解决方案1】:

    问题是您在回调函数中检查 .hasClass,这是在 angulars 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);
        }
    
    }]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2013-09-23
      • 2015-09-27
      相关资源
      最近更新 更多