检查对象是否为空,使用 n- 显示但不是从控制器?

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

$scope.items = {};

我还有一个 $http 请求,它用项目填充这个对象。我想检测这个项目是否为空,似乎 n- 显示支持这个... 我输入

ng-show="items"

奇迹般地,它工作了,我也想做同样的从控制器,但我似乎不能让它工作,似乎我可能不得不迭代对象,看看它是否有任何属性或使用 loash 或下划线。

还有别的选择吗?

我试过了

alert($scope.items == true);

但是在创建对象并用 $http填充时,它总是返回 false,所以它不是这样工作的。

333062 次浏览

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

$scope.items = null;

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
}

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

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

In a private project a wrote this filter

angular.module('myApp')
.filter('isEmpty', function () {
var bar;
return function (obj) {
for (bar in obj) {
if (obj.hasOwnProperty(bar)) {
return false;
}
}
return true;
};
});

usage:

<p ng-hide="items | isEmpty">Some Content</p>

testing:

describe('Filter: isEmpty', function () {


// load the filter's module
beforeEach(module('myApp'));


// initialize a new instance of the filter before each test
var isEmpty;
beforeEach(inject(function ($filter) {
isEmpty = $filter('isEmpty');
}));


it('should return the input prefixed with "isEmpty filter:"', function () {
expect(isEmpty({})).toBe(true);
expect(isEmpty({foo: "bar"})).toBe(false);
});


});

regards.

Or you could keep it simple by doing something like this:

alert(angular.equals({}, $scope.items));

another simple one-liner:

var ob = {};
Object.keys(ob).length // 0

If you couldn't have the items OBJ equal to null, you can do this:

$scope.isEmpty = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};

and in the view you can do:

<div ng-show="isEmpty(items)"></div>

You can do

var ob = {};
Object.keys(ob).length

Only if your browser supports ECMAScript 5. For Example, IE 8 doesn't support this feature.

See http://kangax.github.io/compat-table/es5/ for more infos

Or, if using lo-dash: _.empty(value).

"Checks if value is empty. Arrays, strings, or arguments objects with a length of 0 and objects with no own enumerable properties are considered "empty"."

if( obj[0] )

a cleaner version of this might be:

if( typeof Object.keys(obj)[0] === 'undefined' )

where the result will be undefined if no object property is set.

you can check length of items

ng-show="items.length"

Check Empty object

$scope.isValid = function(value) {
return !value
}