我试图根据点击获得活跃的课程长度。如果我使用超时,那么只能得到确切的计数。如何在不使用超时的情况下实现精确的活动类长度。
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
a {
text-decoration:none;
}
.active {
color:orange;
}
</style>
</head>
<body ng-app="sample">
<div ng-controller="test">
<div data-ng-init="names=[{name:'XML'},{name:'Java'},{name:'Tutorial'}]">
<ul>
<li data-ng-repeat="myObject in names"><a href="javascript:void(0);" ng-model="toggle" ng-class="toggle ? 'active' : ''" ng-click="toggle=!toggle; getActiveLength();">{{myObject.name}}</a></li>
</ul>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script type="text/javascript">
angular.module('sample',[]).controller('test', function($scope, $timeout){
$scope.getActiveLength = function() {
$timeout(function(){
var total = angular.element(document.querySelectorAll(".active")).length;
console.log("Length " + total);
},500)
}
})
</script>
</body>
</html>
请建议我寻求更好的解决方案。
答案 0 :(得分:0)
当您点击锚标记时会发生一些事情:
toggle
值已更改getActiveLength()
被称为调用getActiveLength()
时,虽然toggle
的值已更改,但由于角度$digest进程未完成,因此无法反映DOM。因此,您需要使用$scope.$$postDigest
检查摘要过程中的活动元素。
angular.module('sample',[]).controller('test', function($scope){
$scope.getActiveLength = function(myObject) {
$scope.$$postDigest(function () {
var total = angular.element(document.querySelectorAll(".active")).length;
console.log("Length " + total);
});
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="test">
<div data-ng-init="names=[{name:'XML'},{name:'Java'},{name:'Tutorial'}]">
<ul>
<li data-ng-repeat="myObject in names">
<a href="javascript:void(0);" ng-class="toggle ? 'active' : ''" ng-click="toggle=!toggle; getActiveLength();">{{myObject.name}}
</a>
</li>
</ul>
</div>
</div>
</body>
&#13;