13

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 2

15

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

Sign up to request clarification or add additional context in comments.

4 Comments

Not sure but you could probably write the isEmpty function like: return angular.equals({}, obj); turning it into 1-liner.
Does anyone know why this doesn't work -- i.e., trying to inline the call to angular.equals()?: <div ng-show="angular.equals({},sources)">EMPTY</div>
Thanks, I've added the isEmpty function to my scope. I was hoping there would be a good solution that could be done straight on the html, but at least this is concise and generic.
@MarkRajcok You are only allowed basic expressions, and functions that are defined within the current scope. The angular namespace is outside of the scope.
0

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

1 Comment

Of course, you will need to remember to set $scope.empty to false any time sources is repopulated for any reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.