我正在尝试限制 ng-hide/ng-show 的调用。目前,它的作用是多次调用 getLicense 函数,这会导致浏览器过载。
$scope.getLicense = function( value ) {
if( $sessionStorage.license === '' ) {
DashboardService.getLicense( ).then( function( data ) {
$scope.licenses = data;
var arr = [ ],
id = '';
for( var i in $scope.licenses ) {
arr.push( [ i ] );
}
$sessionStorage.license = arr;
} );
for( var cnt = 0; cnt < $sessionStorage.license.length; cnt++ ) {
if( $sessionStorage.license[ cnt ] == value ) {
console.log( 'true' );
return true;
break;
} else {
return false;
break;
}
}
} else {
for( var cnt = 0; cnt < $sessionStorage.license.length; cnt++ ) {
if( $sessionStorage.license[ cnt ] == value ) {
console.log('true');
return true;
break;
} else {
console.log('false');
return false;
break;
}
}
}
};
我的 HTML 代码如下所示:
<md-list-item class="md-caption" ng-class="{'active': $state.includes('security.webcontrol')}" translate="SIDEBAR.NAV.WEBCONTROL.TITLE" ng-hide="getLicense('web_control_da')">
最佳答案
为 ng-show
/hide
/if
/等提供函数是一种非常糟糕的做法。
每次调用 $digest
时(经常)它都会检查每个观察者以查看其是否已更改。因此,它必须执行您的函数才能知道结果是否不同(或没有)。
在函数 getLicense
中添加 console.log('function returned')
,您将看到它的调用频率。
为了避免这种情况(就像Icycool解释的那样),您必须将其替换为作用域中的 bool 值。并且仅在应该测试 getLicense
时更改 bool 值。
例如:如果每次$sessionStorage.license
更改时都需要计算getLicense
(例如):
$scope.licence = getLicense();
$scope.watch("$sessionStorage.license", function (newValue, oldValue){
$scope.licence = getLicense();
});
在您的 View /模板中:ng-hide="licence"
因此,只有当它确实重要时,它才会执行您的getLicense
。
关于javascript - ng-show/ng-hide 限制多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31160473/