1

I want to use a different template within a repeated block based on the type of data that I am repeating. In my example, the array could contain data or it could contain tweet objects from Twitter. Currently my code looks like this...

<ul data-ng-hide="sourceIsTwitter()" collapse="!showStrings">
    <li data-ng-repeat="matchedString in matches">{{matchedString}}</li>
</ul>
<ul data-ng-show="sourceIsTwitter()" collapse="!showStrings">
    <li data-ng-repeat="tweet in matches">
        {{ tweet.text }} 
        <i>{{ tweet.user.name }}</i>
        <a href="{{ tweetUrl(tweet) }}">{{ formatDateFromTwitter(tweet.created_at) }}</a>
    </li>
</ul>

... and throws lots of errors when the content source isn't Twitter. How should I restructure this to use the right template based on the type of the object? Assume that matches is an array of objects and each object has a property type that I can check.

2 Answers 2

2

You would probably be best served by the ngSwitch directive:

<li data-ng-repeat="obj in matches" data-ng-switch="obj.type">
    <span data-ng-switch-when="twitter"><!-- Do Twitter Rendering --></span>
    <span data-ng-switch-when="facebook"><!-- Do Facebook Rendering --></span>
    <span data-ng-switch-when="foo"><!-- Do Foo Rendering --></span>
</li>
Sign up to request clarification or add additional context in comments.

Comments

1

I had this situation with lots of possible templates - which made ng-switch a bit clunky looking. I put each template in it's own html file and used ng-include with a scope function to retrieve the correct template name:

<ul>
    <li data-ng-repeat="match in matches">
        <div ng-include="getTemplate(match)"></div>
    </li>
</ul>

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.