Nam*_*mal 17 angularjs ng-show ng-hide
我在AngularJS中有简单的应用程序.我想在发出AJAX请求时动态显示消息.不幸的是,它始终处于隐藏状态,我无法弄清楚原因.
HTML:
<div ng-show="message">
<h2>show</h2>
</div>
<div ng-hide="!message">
<h2>Hide</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
AngularJS控制器:
function merchantListController($scope, $http, $rootScope, $location, global) {
$http({
method: 'POST',
url: global.base_url + '/merchant/list',
}).success(function($data) {
if ($data.status === 'success') {
$scope.merchants = $data.data;
$scope.$apply(function(){
$scope.message = true;
});
}
});
}
Run Code Online (Sandbox Code Playgroud)

pix*_*its 22
它不起作用的可能原因是因为您正在子范围内创建新的范围属性,而不是message像您预期的那样覆盖merchantListController范围内的属性.
// The following assignment will create a 'message' variable
// in the child scope which is a copy of the scope variable
// in parent scope - effectively breaking two-way model binding.
$scope.message = true;
Run Code Online (Sandbox Code Playgroud)
要解决此问题,请确保通过引用绑定到模型上的属性而不是绑定到作用域上的属性.
HTML
<div ng-show="my.message">
<h2>show</h2>
</div>
<div ng-hide="!my.message">
<h2>Hide</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
调节器
function merchantListController($scope, $http, $rootScope, $location, global) {
// Initialize my model - this is important!
$scope.my = { message: false };
$http({
method: 'POST',
url: global.base_url + '/merchant/list',
}).success(function($data) {
if ($data.status === 'success') {
$scope.merchants = $data.data;
// modify the 'message' property on the model
$scope.my.message = true;
}
});
});
Run Code Online (Sandbox Code Playgroud)
说明
这样做的原因是因为my使用范围继承规则来解析模型.也就是说,如果my在当前作用域中不存在,则my在父作用域中搜索,直到找到它,或者搜索在$ rootScope处停止.找到模型后,message属性将被覆盖.
显示/隐藏逻辑是错误的......改变它:ng-hide ="message"
<div ng-show="message">
<h2>show</h2>
</div>
<div ng-hide="message">
<h2>Hide</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
ng-hide需要变量何时隐藏,ng-show需要它何时显示,因此条件ng-show ="message"&ng-hide ="!message"是相同的.
试着这样做:
<div ng-show="message">
<h2>show</h2>
</div>
<div ng-show="!message">
<h2>Hide</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
仅用于测试...将您的http类更改为:
$http({
method: 'POST',
url: global.base_url + '/merchant/list',
}).success(function($data) {
$scope.message = true;
}).error(function($data) {
$scope.message = false;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56624 次 |
| 最近记录: |