AngularJS-如何在JS中加载绑定到的变量之前不显示HTML元素

AngularJS - how to not display HTML element until the variable it is binded to is loaded in the JS?

本文关键字:变量 显示 元素 HTML JS 绑定 加载 AngularJS-      更新时间:2023-09-26

这是我的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>

所以基本上,如果ctrl.userProfile.followingtrue,我想隐藏"跟随"按钮并显示"不允许"按钮,反之亦然。

这是我的后端:

self.userProfile = {};
function fetchUserProfile() {
    $http.get('/users/' + username)
    .then(function(response) {
        self.userProfile = response.data;
    }, function(response) {
        self.cerrorMessages = BaseService.accessErrors(response.data);
    });
};
fetchUserProfile();

因此,我获取userProfile,然后用watching变量更新self.userProfile(当我执行self.userProfile = response.data时会发生这种情况。话虽如此,有没有办法告诉HTML在self.userProfile填充watching变量之前不要显示按钮?

创建一个userProfile.ready标志,并使用它来控制FollowUnfollow按钮的显示。

HTML

<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>

JS-

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();

有几种方法可以做到这一点。这里有一个:

如果您从一个空对象开始,并且正在等待promise的解析,那么您可以设置一个范围变量来检查对象的长度。

例如。self.userProfileLength=Object.keys(self.userProfile).length;

在视图中,执行:ng if="ctrl.userProfileLength"(注意:如果您想将元素保留在DOM中,也可以使用ng-show)

Object.keys返回数组中对象的键。长度超过0的任何值都是truthy值,因此它将通过ng-if条件。