Javascript AngularJS-如何在JS中加载绑定到的变量之前不显示HTML元素?
这是我的HTML:Javascript AngularJS-如何在JS中加载绑定到的变量之前不显示HTML元素?,javascript,html,angularjs,Javascript,Html,Angularjs,这是我的HTML: <button type="button" class="btn btn-primary" ng-hide="ctrl.userProfile.following">Follow</button> <button type="button" class="btn btn-primary" ng-show="ctrl.userProfile.following">Unfollow</button> 因此,我获取userProfi
<button type="button" class="btn btn-primary" ng-hide="ctrl.userProfile.following">Follow</button>
<button type="button" class="btn btn-primary" ng-show="ctrl.userProfile.following">Unfollow</button>
因此,我获取
userProfile
,然后使用监视变量更新self.userProfile
(当我执行self.userProfile=response.data
时会发生这种情况。有没有办法告诉HTML在self.userProfile
充满监视变量之前不要显示按钮?有几种方法可以做到这一点。以下是一种:
如果您从一个空对象开始,并且正在等待承诺的解析,那么可以设置一个范围变量来检查对象的长度
e、 g。
self.userProfileLength=Object.keys(self.userProfile).length
在视图中,do:ng if=“ctrl.userProfileLength”
(注意:如果要将元素保留在DOM中,请使用ng show)
Object.keys返回数组中对象的键。长度超过0的任何值都是真实值,因此它将通过ng if条件。创建userProfile.ready
标志,并使用该标志控制Follow
和Unfollow
按钮的显示
HTML
@ismcutler那么你是说我把这两个按钮放在一个容器div
中,这个容器有ng if
语句?然后在GET
请求完成后,我更新self.userProfile
/给它一个长度,这时容器div
将显示出来?@user2719875你可以把它放在cont上A或直接在按钮本身上。一旦您将响应分配给实例变量(userProfile),调用成功解决时,将自动计算长度。对。但是如果我执行ng if=“ctrl.userProfileLength”
(或ng show
并检查长度),则按钮将在ctrl.userProfile
有长度时显示,对吗?我希望按钮的显示取决于ctrl.userProfile.watching
是什么,而不仅仅是当ctrl.userProfile
有长度时。@user2719875 right。在我的示例中,启动新提取时,ready
标志变为false。您的用户可以看到旧的配置文件,但是Follow
或Unfollow
按钮消失,从而防止错误地跟随或取消跟随新的用户配置文件。@georgeawg我认为就绪标志是一个好方法,但是,我不会将其作为响应的同一对象的属性。您正在污染该数据模型。我会将其移出f该对象。
self.userProfile = {};
function fetchUserProfile() {
$http.get('/users/' + username)
.then(function(response) {
self.userProfile = response.data;
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
fetchUserProfile();
<div ng-show="ctrl.userProfile.ready">
<button type="button" ng-hide="ctrl.userProfile.following">Follow</button>
<button type="button" ng-show="ctrl.userProfile.following">Unfollow</button>
</div>
self.userProfile = {};
self.userProfile.ready = false;
function fetchUserProfile() {
self.userProfile.ready = false;
$http.get('/users/' + username)
.then(function(response) {
self.userProfile = response.data;
self.userProfile.ready = true;
}, function(error) {
self.cerrorMessages = BaseService.accessErrors(error.data);
});
};
fetchUserProfile();