简体   繁体   中英

Angularjs: Performance using ng-class

This is a dummy coding that describes my problem
HTML

<div ng-class="{'test': isAllowed }" id='example1'>Example 1</div>
<div ng-class="{'test': isAllowed }" id='example2'>Example 2</div>

$scope.isAllowed is evaluated completely, and #example1 is affected by the class test , but sometimes it takes time for #example2 to be affected by that class, although both of them share same class. I think the problem is with ng-class .
I can fix my problem using ng-if

<div class="test" ng-if="isAllowed" id='example1'>Example 1</div>
<div ng-if="!isAllowed" id='example1'>Example 1</div>
<div class="test" ng-if="isAllowed" id='example2'>Example 2</div>
<div ng-if="!isAllowed" id='example2'>Example 2</div>

As you can see, It looks redundant, and I don't want to deal with the problem in this way

How is isAllowed being set? If it's being set within a setTimeout, setInterval, or something else that is outside of the angular lifecycle, you may need to include a

scope.$apply()

(if its a directive), or

$scope.$apply()

(if its in a controller) after you have set the isActive.

$scope.isActive = true;
$scope.$apply();

If neither of those two work, or if you get a "already in a digest cycle" error, then wrap with an $evalAsync

$scope.$evalAsync(function(){
    $scope.isActive = true;
});

Check out https://jsfiddle.net/cyx4z03m/1/ You will see that the css is not being updated except once every 3 seconds. Open your DevTools and check out the console log. The value is being toggled, but you dont see the real result until angular knows its ready to update. I'm wondering if your issue is related.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM