我正在纠结如何让 ngShow 在指定的超时时间内确定表达式,事实证明 Angular 可以计算表达式但无法反射(reflect) View 中的变化,这是我使用的代码
(查看)
<button
type="button"
class="btn btn-primary rule-fade"
tooltip="{{ proLang.tooltip.ruleApplyBtnTxt }}"
ng-click="applyRule('basic')"
ng-show="showApplyBtns(selectedRules, selectedObj)"
>
<span class="glyphicon glyphicon-dashboard"></span>
Apply Rules
</button>
( Controller ) 以及实现showApplyBtn函数的 Controller
//determine whether apply buttons should be shown
$scope.showApplyBtns = function(selectedRules, selectedObj) {
$timeout(function() {
return selectedRules.length == 1 && selectedObj.length == 1;
},500);
};
Angular 可以确定结果(true 或 false),但 View 似乎没有反射(reflect)变化。
任何帮助将不胜感激,谢谢!
最佳答案
与其让 showApplyBtns
返回一个值,不如尝试将一个值分配给范围变量。
然后您的按钮
可以将该值绑定(bind)到ng-show
<button
type="button"
class="btn btn-primary rule-fade"
tooltip="{{ proLang.tooltip.ruleApplyBtnTxt }}"
ng-click="applyRule('basic')"
ng-show="showApplyBtns"
>
然后更改您的 Controller ,以便 applyRule()
调用 updateShowAppyBtns
,这将更新绑定(bind)变量 showApplyBtns
$scope.applyRule(...) {
...
$scope.updateShowApplyBtns();
}
//determine whether apply buttons should be shown
$scope.updateShowApplyBtns = function() {
$timeout(function() {
$scope.showApplyBtns = $scope.selectedRules.length == 1 && $scope.selectedObj.length == 1;
},500);
};
现在,当调用 updateShowApplyBtns
时,$timeout
函数将更新 $scope.showApplyBtns
,因为更新后的值现在绑定(bind)到 ng-show
在你的按钮上,你的按钮的可见性将被更新。
解释
您遇到的问题是您的 showApplyBtns
实际上没有返回值
$scope.showApplyBtns = function(selectedRules, selectedObj){
$timeout(function(){
return selectedRules.length == 1 && selectedObj.length == 1;
},500);
// return undefined (this is what actually happens here)
};
传递给 $timeout
的匿名函数返回一个值...但是这个值被吞没在 $timeout
函数中并且 showApplyBtns
是没有返回任何东西,因此它返回默认值 undefined
。
如您所想,showApplyBtns
在返回其自身值之前等待 $timeout
完成是不合适的,因为那样会阻塞 i/o(它会在等待时停止所有执行,这在设计上很难在 javascript 中完成)。
因为 showApplyBtns
不能等到 $timeout
返回一个值才返回它自己的值,所以除了利用状态的持久性来管理更新(如我上面的回答所示)。
希望对您有所帮助。 :)
关于javascript - ngShow 超时未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237406/