Search code examples
javascriptangularjsangularjs-directiveangularjs-controller

How can I pull a specific title from an array using Angular?


I am trying to pull a specific title from an array using Angular. Whilst I can use ng-repeat to loop through all titles and print these to my news listing webpage, I only wish to pull the first heading in my array for the news details page. Do I need to use the ng-repeat or can I use something different?

I have tried using number:0 as well as json:0.

$scope.newsListings = [
    {
    title: "Why cooking is great";
    },
    {
    title: "Windsurfing is fun";
    }
];


<div ng-controller="primaryController">
    <article>
        <div ng-repeat="item in newsListings | json:0">
            <h1>{{item.title }}</h1>
            <p class="synopsis">{{item.synopsis}}</p>
        </div>
    <article>
</div>

Solution

  • If you want to show only one item, you can omit the ng-repeat part as you want only one item from your array. You need just to use index.

    <div ng-controller="primaryController">
        <article>
            <div>
                <h1>{{ newsListings[0].title }}</h1>
                <p class="synopsis">{{ newsListings[0].synopsis }}</p>
            </div>
        <article>
    </div>