检查对象是否为空,是否适用于 ng-show 但不适用于控制器? [英] Checking if object is empty, works with ng-show but not from controller?

查看:22
本文介绍了检查对象是否为空,是否适用于 ng-show 但不适用于控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样声明的 JS 对象

I have a JS object declared like so

$scope.items = {};

我还有一个 $http 请求,它用项目填充这个对象.我想检测这个项目是否为空,看来ng-show支持这个...我输入

I also have a $http request that fills this object with items. I would like to detect if this item is empty, it appears that ng-show supports this... I enter

ng-show="items"

神奇地它有效,我也想从控制器做同样的事情,但我似乎无法让它工作,看来我可能必须遍历对象以查看它是否有任何属性或使用lodash 或下划线.

and magically it works,I would also like to do the same from a controller but i can't seem to get it to work, it appears I may have to iterate over the object to see if it has any properties or use lodash or underscore.

有其他选择吗?

我确实尝试过

alert($scope.items == true);

但它总是返回 false ,当对象被创建并用 $http 填充时,所以它不能那样工作.

but it always returns false , when the object is created and when populated with $http, so its not working that way.

推荐答案

这里不需要使用空对象字面量,可以使用 null 或 undefined :

Use an empty object literal isn't necessary here, you can use null or undefined:

$scope.items = null;

这样,ng-show 应该继续工作,在你的控制器中你可以这样做:

In this way, ng-show should keep working, and in your controller you can just do:

if ($scope.items) {
    // items have value
} else {
    // items is still null
}

并且在您的 $http 回调中,您执行以下操作:

And in your $http callbacks, you do the following:

$http.get(..., function(data) {
    $scope.items = {
        data: data,
        // other stuff
    };
});

这篇关于检查对象是否为空,是否适用于 ng-show 但不适用于控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆