devel0pp3r
devel0pp3r

Reputation: 105

Check if array has a particular index in AngularJs

In AngularJS expressions, how can I check if an array has value in a particular index or not? Consider the following example

$scope.arr =['one','two','three'];

In HTML.

<p ng-show="arr[3]!=''">{{arr[3]}}</p>

Upvotes: 2

Views: 2368

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

You have to compare with undefined.

<p ng-show="arr[3]!=undefined">{{arr[3]}}</p>

function MyCtrl($scope) {
  $scope.arr =['one','two','three'];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
       <p ng-show="arr[2]!=undefined">{{arr[2]}}</p>
  </div>
</div>

Also, you can define a function which check if an array has value in a particular index, using typeof operator.

function isDefined(arrayElement) {
      return typeof arrayElement!== 'undefined';
}

function MyCtrl($scope) {
  $scope.arr =['one','two','three'];
  $scope.isDefined=function(arrayElement){
      return typeof arrayElement!== 'undefined';
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
       <p ng-show="isDefined(arr[3])">{{arr[3]}}</p>
       <p ng-show="!isDefined(arr[3])">undefined</p>
  </div>
</div>

Upvotes: 3

Related Questions