Rich Rich - 9 days ago 6
AngularJS Question

AngularJs ng-repeat not working with more than one item in ng-init

I'm new to AngularJs and working through an example which is not working correctly using ng-init and ng-repeat. This is part of my code from the body

<div ng-app="" ng-init="books=[
{title:'Pride and Prejudice', author:'Jane Austen', genre:'Romance'}
{title:'Dracula', author:'Bram Stoker', genre:'Horror'}
{title:'The Hobbit', author:'J.R.R. Tolkien', genre:'Fantasy'}
]">

<p>Here are your books:</p>
<ol>
<li ng-repeat="book in books">
{{ 'Title: ' + book.title + ', Author: ' + book.author + ', Genre: ' + book.genre }}
</li>
</ol>
</div>


If I remove the lines for Dracula and The Hobbit, the data does display but with all three books no data is displayed.

Answer

You are missing the commas to separate your array items.

<div ng-app="" ng-init="books=[
    {title:'Pride and Prejudice', author:'Jane Austen', genre:'Romance'},
    {title:'Dracula', author:'Bram Stoker', genre:'Horror'},
    {title:'The Hobbit', author:'J.R.R. Tolkien', genre:'Fantasy'}
    ]">

    <p>Here are your books:</p>
    <ol>
        <li ng-repeat="book in books">
            {{ 'Title: ' + book.title + ', Author: ' + book.author + ', Genre: ' + book.genre }}
        </li>
    </ol>
</div>

Array syntax

[element0, element1, ..., elementN]

Comments