Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statement to check if an array is empty with angular JS

I have this function:

$scope.doPaste = function(destination) {                            
   if ($scope.selectCopy.ids != []) {
       console.log("will copy");
       $scope.CopyFiles(destination);
   }
   if ($scope.selectMove.ids != []) {
       console.log("will move");
       $scope.MoveFiles(destination);
   }                                
};

In my app, $scope.selectMove.ids and $scope.selectCopy.ids can't be both non-empty. I mean for example when $scope.selectMove.ids is non-empty $scope.selectCopy.ids is empty.

My problem is that in the console, I always see both will copy and will move.

like image 929
Yuri Avatar asked Apr 23 '15 15:04

Yuri


2 Answers

Note [] != [] return true (because they are different objects).

You should use length to check whether an array is empty.

if($scope.selectCopy.ids.length > 0){
     console.log("will copy");
     $scope.CopyFiles(destination);
}
like image 161
xdazz Avatar answered Oct 05 '22 11:10

xdazz


I think you should check by angular.isObject() which would return true if it is an object.

$scope.doPaste = function(destination) {
   if (angular.isObject($scope.selectCopy.ids) && $scope.selectCopy.ids.length > 0) {
       console.log("will copy");
       $scope.CopyFiles(destination);
   }

   if (angular.isObject($scope.selectMove.ids) && $scope.selectMove.ids.length > 0){
       console.log("will move");
       $scope.MoveFiles(destination);
   }                               
};
like image 28
Pankaj Parkar Avatar answered Oct 05 '22 13:10

Pankaj Parkar