0

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:

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

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

Thanks

3 Answers 3

1

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.

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

5 Comments

what's with the if in the interpolation? How does that create expected output?
@charlietfl Angular can interpolate conditionals.
@jusopi fine but wouldn't produce expected results that way... it does now after edit
agreed, plus he's modified his answer so it's a moot point now
All great answers IMO, but this was the best solution for me
1

Do the logic on the controller (assign to a different variable for array and string) - then just do the dumb logic in the view:

if (Array.isArray($scope.myvalue)) {
    $scope.myArray = $scope.myvalue;
} else {
    $scope.myString = $scope.myvalue;
}

And the view

<div>
    <div ng-if="myArray">
        <span ng-repeat="v in myArray">{{v}}</span>
    </div>
    <div ng-if="myString">
        {{myString}}
    </div>
</div>

Comments

1

make a simple getter

$scope.getVal = function( vals ){
    if(Array.isArray(vals)) return vals
    else return [ vals ]
}

then instead of ng-if AND ng-repeat just use the repeater as you normally would.

<div ng-repeat="val in getVal(vals)"> {{ val }} </div>

4 Comments

There's a nuance to my specific situation where this won't work, but I can see how it would in others. Upvote
Can you explain the specifics?
I'm actually wrapping the array elements in another element that won't be present with the string value, as there's additional user interaction with the elements created by the array.
Ahhh ok I see. In that case I would drive this by a filter and use the ng-if. I really dislike adding this kind of logic to the controllers.

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.