admin管理员组

文章数量:1434371

Running in to a frustrating issue with AngularJS. All I'm trying to do is load a json file and display it in the template using ng:repeat. I've not had any issue with this in the past but for some reason, the code below doesn't work. Can someone take a look and tell me what I'm missing?

If you look at the template:

palette.html

{{palette}}

<div ng-repeat="for color in palette">{{color}}</div>

{{palette}} outputs [{"hex":"#6e4516"},{"hex":"#DDDABE"},{"hex":"#ECEAD9"},{"hex":"#98A349"},{"hex":"#798616"}] however the ng:repeat displays nothing. So the json is being loaded in to the scope but for some reason I can't loop over it.

Here is my main js file:

app.js

var App = angular.module('App', []).
    config(function($routeProvider)
    {
        $routeProvider.
            when('/palette', {templateUrl:'templates/palette.html', controller:PaletteController}).
            otherwise({redirectTo:'/home'})
    });

function PaletteController($scope, $http){
    $http.get('palette.json').success(function(palette){
        $scope.palette = palette;
    });
}

and the data being loaded from the json file:

palette.json

[
    {"hex": "#6e4516"},
    {"hex": "#DDDABE"},
    {"hex": "#ECEAD9"},
    {"hex": "#98A349"},
    {"hex": "#798616"}
]

Running in to a frustrating issue with AngularJS. All I'm trying to do is load a json file and display it in the template using ng:repeat. I've not had any issue with this in the past but for some reason, the code below doesn't work. Can someone take a look and tell me what I'm missing?

If you look at the template:

palette.html

{{palette}}

<div ng-repeat="for color in palette">{{color}}</div>

{{palette}} outputs [{"hex":"#6e4516"},{"hex":"#DDDABE"},{"hex":"#ECEAD9"},{"hex":"#98A349"},{"hex":"#798616"}] however the ng:repeat displays nothing. So the json is being loaded in to the scope but for some reason I can't loop over it.

Here is my main js file:

app.js

var App = angular.module('App', []).
    config(function($routeProvider)
    {
        $routeProvider.
            when('/palette', {templateUrl:'templates/palette.html', controller:PaletteController}).
            otherwise({redirectTo:'/home'})
    });

function PaletteController($scope, $http){
    $http.get('palette.json').success(function(palette){
        $scope.palette = palette;
    });
}

and the data being loaded from the json file:

palette.json

[
    {"hex": "#6e4516"},
    {"hex": "#DDDABE"},
    {"hex": "#ECEAD9"},
    {"hex": "#98A349"},
    {"hex": "#798616"}
]
Share Improve this question asked Dec 9, 2012 at 18:12 KyleeKylee 1,6752 gold badges32 silver badges55 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

You're code within the expression section of ng-repeat is incorrect. You need something like this:

<div ng-repeat="color in palette">{{color.hex}}</div>

本文标签: javascriptCan39t loop over array in AngularJS templateStack Overflow