![](/img/trans.png)
[英]Why is this simple AngularJS ng-show is not working to show sublist?
[英]Why is this simple AngularJS ng-show not working?
我无法弄清楚为什么我的简单AngularJS应用程序无法正常工作。 “加载......”应该被隐藏,并且“完成!” 应在1秒后显示。
HTML:
<div ng-app>
<div ng-controller="TestCtrl">
<div class="text-center" ng-show="loading">
<h1>Loading...</h1>
</div>
<div class="text-center" ng-show="!loading">
<h1>Done!</h1>
</div>
</div>
</div>
使用Javascript:
function TestCtrl($scope) {
$scope.loading = true;
setTimeout(function () {
$scope.loading = false;
}, 1000);
}
你需要告诉angular你更新了var:
function TestCtrl($scope) {
$scope.loading = true;
setTimeout(function () {
$scope.$apply(function(){
$scope.loading = false;
});
}, 1000);
}
要不就
function TestCtrl($scope, $timeout) {
$scope.loading = true;
$timeout(function () {
$scope.loading = false;
}, 1000);
}
更好的方法是调用$scope.$digest();
更新您的用户界面
你需要使用$timeout
并将其注入你的控制器:
function TestCtrl($scope, $timeout) {
$scope.loading = true;
$timeout(function () {
$scope.loading = false;
}, 1000);
}
编辑:删除$scope.apply();
正如@Salman建议的那样
您想使用apply()
函数来停止加载消息。
检查这个演示jsFiddle **。
JavaScript的:
function TestCtrl($scope) {
$scope.loading = true;
setTimeout(function () {
$scope.$apply(function(){
$scope.loading = false;
});
}, 1000);
}
希望这会对你有所帮助!
当fire angle事件发生到像setTimeout这样的另一个对象时你应该使用
$scope.$apply(function(){
$scope.loading = false;
});
例如
var loading={
show:function(){
$scope.loading=true
},
hide:function(){
$scope.loading=false
}
}
可能不是最好的方式
var loading={
show:function(){
$scope.$apply(function(){
$scope.loading=true
});
},
hide:function(){
$scope.$apply(function(){
$scope.loading=false
});
}
}
我发现一种解决ng-show无法以你想要的方式进行评估的方法是使用ng-class代替。
<div class="mycontent" data-ng-class="{'loaded': !loading}">
这种方式当$ scope.loading不等于true时,css类'loaded'将被添加到元素中。 然后你只需要使用css类来显示/隐藏内容。
.mycontent {
display: none;
}
.loaded {
display: block;
}
我认为这里最大的问题是你使用原语作为你的模型。 角度团队建议使用一个对象来绑定模型。 例如:
scope.model = {};
scope.model.loading = false;
然后在你的HTML中:
<div class="text-center" ng-show="model.loading">
这样,angular获取对象内部字段的引用,而不是变量指向的基元。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.