最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angularjs default text for empty ng-repeat on javascript object - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question asked Dec 12, 2012 at 17:35 psionicgamespsionicgames 2374 silver badges8 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 16

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.

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

发布评论

评论列表(0)

  1. 暂无评论