Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.x Directive With A Template

Tags:

angularjs

I'm trying to create an angular directive for forming sentences. The goal is to take a list and iterate through them as necessary. The result of the directive would be something like:

shoes, pants and socks

or

shoes, pants and +5 more

I have the basic directive setup to work with a array of strings - but I'd like to customize it to allow custom templates for each sentence element (i.e. hyperlinks, styling, etc). That is:

<sentence values="article in articles">
<strong>{{article.title}}</strong> by <span>{{article.author}}</span>
</sentence>

The HTML the user sees in the browser needs to be something like:

$scope.articles = [
  { title: '...', author: '...'},
  { title: '...', author: '...'},
  ...
]

<span><strong>ABC</strong> by <span>123</span></span>
<span>, </span>
<span><strong>DEF</strong> by <span>456</span></span>
<span>and</span>
<span>+5 more</span>

I'm guessing it has something to do with transclude but cannot figure out the API. I've also experimented with using ng-repeat instead of the directive template but wasn't able to find a solution.

like image 860
Stussa Avatar asked Feb 25 '26 16:02

Stussa


1 Answers

Something like this should work where maxArticles is a number defined on your scope

<sentence values="article in articles | limitTo: maxArticles">
    <strong>{{article.title}}</strong> by <span>{{article.author}}</span>
    <span ng-if="$index < maxArticles - 2">, </span>
    <span ng-if="$index === articles.length - 1 && articles.length <= maxArticles">and</span>
</sentence>
<span ng-if="articles.length > maxArticles">
    and +{{articles.length - maxArticles}} more.
</span>
like image 64
rob Avatar answered Feb 28 '26 07:02

rob