![](/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.