Ng-Show多次通话 [英] Ng-Show called multiple times

查看:63
本文介绍了Ng-Show多次通话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

此外,如果有人有任何建议可以改进此建议或IF陈述,则将是有用的.谢谢你.

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

推荐答案

ng-show将在每个摘要循环中进行评估-它不知道(在该抽象级别上)在ng-show中进行了什么检查,因此必须只要结果可以更改,请重新评估.您可能想做的事情是这样的:

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.

这篇关于Ng-Show多次通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆