Joe Conlin
Joe Conlin

Reputation: 5994

API JSON response using ng-repeat in AngularJS

I'm having a weird issue using ng-repeat on the JSON response from the Google PageSpeed API. Basically, I have it working BUT it is oddly returning an odd BLANK UL before followed by the correct reply.

Test page: http://staging.converge.io/test-json

My controller: (will change the API key once this gets answered)

function FetchCtrl($scope, $http, $templateCache) {
    $scope.method = 'GET';
    $scope.url = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=http://www.web.com&key=AIzaSyA5_ykqZChHFiUEc6ztklj9z8i6V6g3rdc';
    $scope.key = 'AIzaSyA5_ykqZChHFiUEc6ztklj9z8i6V6g3rdc';
    $scope.strategy = 'mobile';

    $scope.fetch = function() {
        $scope.code = null;
        $scope.response = null;

        $http({method: $scope.method, url: $scope.url + '&strategy=' + $scope.strategy, cache: $templateCache}).
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
        }).
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
        });
    };

    $scope.updateModel = function(method, url) {
        $scope.method = method;
        $scope.url = url;
    };
}

HTML:

            <ul ng-repeat="formattedResult in data.formattedResults">
                <li ng-repeat="ruleResult in formattedResult">
                    <h4>{{ruleResult.localizedRuleName}}</h4>
                    <strong>Impact score</strong>: {{ruleResult.ruleImpact*10 | number:0}}
                </li>
            </ul>

Thanks for any help!

Upvotes: 2

Views: 2294

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

As I can see in the response, formattedResults is not an array, it's an object containing an array of ruleResults. You need to change the way you access your data.

Replace:

<ul ng-repeat="formattedResult in data.formattedResults">
            <li ng-repeat="ruleResult in formattedResult">
                <h4>{{ruleResult.localizedRuleName}}</h4>
                <strong>Impact score</strong>: {{ruleResult.ruleImpact*10 | number:0}}
            </li>
        </ul>

With

<ul>
     <li ng-repeat="ruleResult in data.formattedResults.ruleResults">
             <h4>{{ruleResult.localizedRuleName}}</h4>
             <strong>Impact score</strong>: {{ruleResult.ruleImpact*10 | number:0}}
     </li>
</ul>

Upvotes: 1

Related Questions