-1

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>
Al-76
  • 1,738
  • 6
  • 22
  • 40
  • 1
    That's not [JSON](http://json.org). _"JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML."_ - [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). `newListings` is just an array of _objects_. – Andreas Apr 07 '18 at 11:46

2 Answers2

2

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>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

You can actually use ng-model for this with a first element of array if you need 2 way binding as well (for inputs of course). For other purposes you can use just index.

<div ng-controller="primaryController">
<article>
    <div>
       <input type="text" ng-model="newsListings[0].title" />
    </div>
    <div ng-bind="newsListings[0]">
        <h1>{{newsListings[0].title }}</h1>
        <p class="synopsis">{{newsListings[0].synopsis}}</p>
    </div>
<article>
</div>
Mirko Acimovic
  • 508
  • 2
  • 9