简体   繁体   中英

Issues getting "ng-repeat" to repeat.

I have been trying this for awhile and I am not getting it. I looked at the documentation and I think it is my syntax.

My HTML:

<div ng-controller="StoreController as store">
    <div ng-repeat="item in store.items">
        <img ng-src="{{item.ImageSets.ImageSet[0].SmallImage.URL}}" />
    </div>
</div>

My Controller:

(function() {
    var app = angular.module("store", []);

    app.controller("StoreController", ["$http", function($http) {
        var store = this;
        store.items = []
        $http.get("/amazon.json").success(function(data) {
            store.items = data.Items
        });
    }]);
})();

And this is my object.

{
 "Items": {
     "Item": {...},
     "Item": {...},
     "Item": {...},
     "Item": {...}
  }
}

The code is working. But I am only getting it to display one image instead of 4 images. I am new to angular and think it is a syntax issue.

This is not an angular issue, it's a JavaScript one. The thing is, you are trying to build an object with multiple times the same key ( item ). So every time you add a new item to the object, the previous one gets erased. That is why your object only has a single item.

So doing :

var items = {
  "item": 1,
  "item": 2,
}

is equivalent to :

var items = {};
items["item"] = 1;
items["item"] = 2; //items["item"] gets replaced and its value is now 2

Instead you should use an array that contains all the items. Like that

{
    items: [
        {...},
        {...},
        //...
    ]
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM