Reputation: 97
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
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
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