AngularJS display list from an array


I have a controller that returns an array, I'm trying to display every element of that array as a list.

What I am attempting to do, which is not working:

<li ng-repeat="Name in names">
    <a ng-controller="PostsCtrl" href="#">{{response.text}}</a>

response.text returns an array from the controller.

I am also wondering, what is the value of the ng-repeat attribute supposed to be, any unique string?

Thank you!

Problem courtesy of: StackPWRequirmentsAreCrazy


Define the array in your controller with the $scope variable:

app.controller('PostsCtrl', function($scope) {
    $scope.response = { text: ['hello', 'world'] };

Then use ng-repeat on the VARIABLE, not the controller.

<div ng-controller="PostsCtrl">
        <li ng-repeat="name in response.text"><a href="#">{{name}}</a></li>

The controller is only used to define what $scope variables you can use in that section, and is not used as a variable itself.

Solution courtesy of: tcase360


ngRepeat is basically just like a for loop. There is no default value, you just need to give it the data you want it to iterate through. So when you're doing a ng-repeat="name in names", it is similar to doing something like for(var name in names){} in plain javascript. For it to work properly you need to pass this data to the template via your $scope, as such:

var myApp = angular.module('myApp', []);

myApp.controller('PostsCtrl', ['$scope', function($scope){
    // Here the array would be your response.text:
    $scope.names = ['John', 'Jessie', 'Johanna', 'Joy', 'Mary', 'Peter', 'Sebastian', 'Erika', 'Patrick', 'Samantha'];

<script src=""></script>
<div ng-app="myApp">
    <div ng-controller="PostsCtrl">
        I have {{names.length}} friends. They are:
          <li ng-repeat="name in names">
            [{{$index + 1}}] {{name}}.

For further reading, please visit:

Discussion courtesy of: Gerson Goulart

You probably have your controller on the wrong attribute there, unless you want a new controller for every item in the array.

The second issue, "response.text returns an array from the controller." So, is this the array you want to repeat?

<div ng-controller="PostsCtrl">
  <li ng-repeat="item in response.text">
      <a href="#">{{item}}</a>

And then the third question, what is the value of the ng-repeat attribute supposed to be: it's supposed to be the value of any valid array on your $scope or viewModel. So, response.text would be a valid item to put on the ng-repeat since it is an array. As I have it above, you now have an item object for every item in reponse.text. If this is as far down as you want to go, you can simply print {{item}} -- if item has properties, you could do something like, for instance, {{item.someProperty}}

Discussion courtesy of: Tom

This recipe can be found in it's original form on Stack Over Flow.