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