Ng-Show多次调用

时间:2014-11-19 19:14:57

标签: javascript angularjs

我有一个附有ng-disable指令的按钮和一个评估按钮状态的函数。当视图加载时,我注意到该函数被调用大约6-8次。这是正常的吗?它不仅在加载时,而且与视图的任何交互:

<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>

然后控制器具有此功能:

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;
    }
}

此外,如果任何人有任何改进此建议或IF语句的建议将是有用的。谢谢。

1 个答案:

答案 0 :(得分:2)

ng-show将在每个摘要周期进行评估 - 它不知道(在该抽象级别)ng-show内检查的内容,因此必须在结果时随时重新评估已经改变了。您可能想要做的是:

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

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

但老实说,如果它不是计算密集型(并且不是这样),那么将其保留为原样可能更容易也更清晰。