Randy Hall Randy Hall - 6 months ago 49
AngularJS Question

Repeat if array, display if string

I am referencing a value in my controller that may be a string or an array. If it's an array, I want to use "ng-repeat" (probably) to list out my items.

If it's a string, I just want to display the string.

Something like:

{{if is array}}
<span ng-repeat="v in myvalue">{{v}}</span>

I'm wondering if there's an elegant way to do this in Angularjs that I'm simply not yet familiar with.



There is angular.isArray method. You can use that. You need to place it in the the scope or vm:

$scope.isArray = angular.isArray

And in HTML

 <span ng-repeat="v in myvalue" ng-if="isArray(myvalue)">{{v}}</span>
 <span ng-if="!isArray(myvalue)">{{myvalue}}</span>

If you are using it in more than one place, best is to go for a directive.