srecce
srecce

Reputation: 97

Check for empty ng-repeat from controller

I'm a newbie in angularjs. And my template is something like this:

<div ng-repeat="item in values"></div>
<div ng-repeat="item1 in values1"></div>

And my controller:

$scope.openItems = function () {
    $http.get('/api/openItems').success(function (data) {
         $scope.values = data;
    });
};

That is working fine. Now I want to show the items, only if it is empty.

I tried something like this:

$scope.openItems = function () {
    $http.get('/api/openItems').success(function (data) {
    if ($scope.values.length == 0) {
         $scope.values = data;
    } else {
         $scope.values1 = data;
    }
    });
};

Any idea how to check from the controller is a ng-repeat has data in it?

Thanks in advance

Upvotes: 1

Views: 821

Answers (2)

ajmajmajma
ajmajmajma

Reputation: 14216

Make sure you are initializing the arrays at the top, then you can just do something like this :

 //initialize vars
 $scope.values = [];
 $scope.values1 = [];


$scope.openItems = function () {
    $http.get('/api/openItems').success(function (data) {
    if ($scope.values.length === 0) {
         //you may or may not want to clear the second array if you are toggling back and forth
         $scope.values1 = [];
         $scope.values = data;
    } else {
         //empty the first one so we make the hide/show logic simple
         $scope.values = [];
         $scope.values1 = data;
    }
    });
};

then your html just looks like

<div ng-show="values.length" ng-repeat="item in values"></div>
<div ng-show="values1.length" ng-repeat="item1 in values1"></div>

Here is a quick proof of concept - http://jsfiddle.net/Lzgts/573/

You can also swap the ng-show with ng-if, if you want the divs to actually be taken off the DOM.

Upvotes: 1

Cody Braun
Cody Braun

Reputation: 657

Depending on how your array is initialized (which we're not seeing) it might not ever have length==0 (for example I think it could be undefined, etc.) you could try:

if ($scope.values.length != 0) {
        $scope.values1 = data; 
    } else {
        $scope.values = data;
    }

Upvotes: 0

Related Questions