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

时间:2015-11-15 01:40:05

标签: 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>

基本上,我想隐藏“关注”按钮,如果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,然后使用self.userProfile变量更新了watching(当我self.userProfile = response.data时就会发生这种情况。有了这个说法,对我有用吗告诉HTML在self.userProfile填充watching变量之前不显示按钮?

2 个答案:

答案 0 :(得分:1)

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

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

e.g。 self.userProfileLength = Object.keys(self.userProfile).length;

在视图中,执行:ng-if =&#34; ctrl.userProfileLength&#34; (注意:如果要将元素保留在DOM中,请使用ng-show)

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

答案 1 :(得分:1)

创建MySpinner spinner1 = (MySpinner) findViewById(R.id.spinner1); Spinner spinner2 = (Spinner) findViewById(R.id.spinner2); String[] itemList = new String[]{ "item1", "item2", "item3" }; ArrayAdapter<String> itemArray= new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, itemList); itemArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(itemArray); spinner2.setAdapter(itemArray); 标记,并使用该标记来控制userProfile.readyFollow按钮的显示。

HTML

Unfollow

JS

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