Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs default text for empty ng-repeat on javascript object

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.

like image 484
psionicgames Avatar asked Dec 12 '12 17:12

psionicgames


People also ask

What is Ng-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What can I use instead of NG-repeat?

But ng-repeat is not the right thing to use when you have large datasets as it involves heavy DOM manipulations. And you should consider using ng-repeat with pagination. You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

How do I remove duplicates in NG-repeat?

You can use unique filter while using ng-repeat . If you use track by $index then unique won't work. ok, I used unique and its working now, thanks!

Where is the last element in NG-repeat?

$first and $last It's common when using ng-repeat to add specific behavior to the first or last element of the loop, e.g. special styling around the edges. Instead, ng-repeat already supplies you with two ready boolean properties. $first is true for the first element, and $last is true for the last element.


1 Answers

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.

like image 69
eterps Avatar answered Sep 27 '22 22:09

eterps