2

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>

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.