Ng-Show called multiple times

I have a button with the ng-disable directive attached and a function to evaluate the button state. When the view loads, I notice that the function is called around 6-8 times. Is this normal? It's not only on load but any interaction with the view :

<button type="button" class="listBtn btn btn-xs btn-block btn-danger" ng-click="Site.deleteSite()" ng-show="Site.canDelete()"><i class="fa fa-times fa-fw"></i> Delete Site</button>

Then the controller has this function:

canDelete: function () {
    console.log(Site.selected);

    //CHECK IF SITE SELECTED
    if (Site.selected) {
        console.log('Site has been selected');
        console.log(Site.selected.children.length);
        //CHECK IF SELECTED HAS CHILDREN
        if (Site.selected.children.length) {
            console.log('Site has children');
            //SELECTED HAS CHILDREN - DISABLE BUTTON
            return true;
        } else {
            //SELECTED HAS NO CHILDREN - ENABLE BUTTON
            console.log('Site has no children');
            return false;
        }
    } else {
        //NO SITE SELECTED - DISABLE BUTTON 
        console.log('No site selected');
        return true;
    }
}

Also, if anyone has any recommendations for improving this or the IF statement that would be useful. Thank you.

Answers:

Answer

ng-show will be evaluated on every digest cycle - it doesn't know (at that level of abstraction) what is checked inside ng-show, so must reevaluate anytime the result could have changed. What you may want to do is something like:

 $scope.canDelete = checkIfCanDelete();
 checkIfCanDelete = function() {
     //your check
     $scope.canDelete = Site.selected && Site.selected.children.length;
 }

 $scope.$watch('Site.selected', function() {
     checkIfCanDelete();
 }        

But honestly, if it's not computationally intensive (and this isn't), it's probably easier and clearer to just leave it as it.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.