I have a problem getting default text to print out for an empty ng-repeat that is iterating over a javascript object. Normally I would just do a <div ng-show="object.length==0">EMPTY SET</div>"
but you can't call length on a javascript object. I have a simple jsfiddle to demonstrate the problem: /. Basically I just need to know when the ng-repeat has no objects to repeat over so I can show some default text. Thanks for any help.
I have a problem getting default text to print out for an empty ng-repeat that is iterating over a javascript object. Normally I would just do a <div ng-show="object.length==0">EMPTY SET</div>"
but you can't call length on a javascript object. I have a simple jsfiddle to demonstrate the problem: http://jsfiddle.net/C4t4LystX/zHJv8/8/. Basically I just need to know when the ng-repeat has no objects to repeat over so I can show some default text. Thanks for any help.
2 Answers
Reset to default 16You are correct, there is no object.length in javascript. Because you are resetting sources to an empty object, you need to check to see if the object is empty, or has some sources. You can write a simple function called isEmpty.
<div ng-show="isEmpty(sources)">
EMPTY SOURCES
</div>
function Ctrl1($scope) {
$scope.sources = {source1:{id:"source1"},source2:{id:"source2"}};
$scope.cleanSources = function(){
$scope.sources = {};
};
$scope.isEmpty = function (obj) {
return angular.equals({},obj);
};
}
http://jsfiddle.net/zHJv8/21/
EDIT: Changed isEmpty to use angular.equals instead of for each loop.
ng-show works from a boolean expression, so all you need is to set something to true when the set is empty, and to false when it has something in it. Here's a fiddle with one way to do it:
Here's the idea:
$scope.cleanSources = function(){
$scope.sources = {};
$scope.empty = true;
};
And here's a working fiddle: http://jsfiddle.net/J38r2/
This method doesn't directly test whether sources is empty. To do that you could:
http://jsfiddle.net/timothybone/HXgbR/4/
And of course the docs show the same idea: http://docs.angularjs.org/api/ng.directive:ngShow