RoboYak
RoboYak

Reputation: 1482

AngularJS NG-Repeat Seems to Not Work on Array with Single Object

I have found many posts about how ng-repeat does not play well with objects, and expects the data to be an array, but my data is an array, it just happens to have a single object(list2). I get list1 fine, and everything works perfect. According to everything that I have found, list2 should work. Anyone know why it doesn't?

Data coming from my factory:

(function(){
var Factory = function(){

    var model =  {
        list1: [
            {
                id: "1_1",
                type: "header",
                headerText: "1_1 Header",
                secondaryHeaderText: "",
                paragraphText: "1_1 Paragraph",
                image: ""
            },
            {
                id: "1_2",
                type: "header",
                headerText: "Header 1_2",
                secondaryHeaderText: "",
                paragraphText: "1_2 Paragraph",
                image: ""
            },
            {
                id: "1_3",
                type: "header",
                headerText: "1_3 Header1",
                secondaryHeaderText: "1_3 Header2",
                paragraphText: "",
                image: ""
            }
        ],
        list2: [
            {
                id: "2_1",
                type: "link",
                headerText: "2_1 Header",
                paragraphText: "2_1 Paragraph",
                linkText: "2_1 Link Text",
                image: ""
            }
        ]
    };

    var factory = {};

    factory.getList1 = function(){
        return model.list1;
    };

    factory.getList2 = function(){
        return model.list2;
    };

    return factory;
};
angular.module('designApp').factory('Factory', Factory);
}());

HMTL

<div>
    <!--works perfectly fine -->
    <div ng-repeat="item in list1" ng-include="'app/partial/list1.html'"></div>
</div>

<div>
     <div ng-repeat="item in list2" ng-include="'app/partial/list2.html'"></div>
</div>

Controller

(function(){
var Controller = function($scope, Factory){
    $scope.list1 = [];
    $scope.list2 = [];


function init(){
    $scope.list1 = Factory.getList1();
    $scope.list2 = Factory.getList2();
}

init();
};

Controller.$inject = ['$scope', 'Factory'];

angular.module('designApp')
    .controller('Controller', Controller);
}());

This is all that is in list2.html. Does not render any of the model data but renders the html tags, and throws no errors.

<h2>{{list2.headerText}}</h2>
<p>{{list2.paragraphText}}</p>

Thanks in advance for any help!

Upvotes: 1

Views: 793

Answers (1)

Patrick Kelleter
Patrick Kelleter

Reputation: 2771

You have to replace

<h2>{{list2.headerText}}</h2>
<p>{{list2.paragraphText}}</p>

by

<h2>{{item.headerText}}</h2>
<p>{{item.paragraphText}}</p>

working plunkr: https://plnkr.co/edit/FC5KPpOl7gsmfva63veq?p=preview

Upvotes: 1

Related Questions