1

I want to display json object in the view. The code is:

<ul ng-repeat="item in items">
    <li ng-repeat="(key, val) in item">
        {{key}}: {{val}}
    </li>
</ul>

In, the controller :

$scope.init = function (){
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            $scope.items = JSON.parse(xhr.responseText);
            console.log(JSON.parse(xhr.responseText));
        }
    };
    xhr.open('GET', 'http://127.0.0.1:8000/user_list/', true);
    xhr.send(null);
}

After console.log I'm getting

[{"user_name": "Pranav", "user_id": 1}, {"user_name": "Sagar", "user_id": 2}]

which I'm not able to manipulate like in previous example.

How to convert it in the format :

$scope.items =
    [
        {"user_name": "Pranav", "user_id": 1},
         {"user_name": "Sagar", "user_id": 2}]
    ];

So, I can use it.

2 Answers 2

1

Your data is in the correct format, however use Angular's $http for AJAX requests as this will trigger a digest cycle and allow the view to update:

$http.get("http://127.0.0.1:8000/user_list/").success(function(data) {
    $scope.items = data;
});
Sign up to request clarification or add additional context in comments.

Comments

1

I created a fiddle here: http://jsfiddle.net/fynva/

I simplified the HTTPGET call in the example since you did not have problem getting the JSON. Here is the code sample.

<div ng-app="myApp">
        <div ng-controller="TextController">
            <div>
                    <label for="spSelectViewMenu">Please select the list to view:</label>
                    <select id="spSelectViewMenu" ng-model="list" ng-options="c.user_name for c in lists"></select><br />
                <ul ng-show="list" ng-repeat="(key, val) in list" >
                    <li>{{key}} : {{val}}</li>
                </ul>
            </div>
    </div>
</div>

<script>
var myAppModule = angular.module('myApp', []);
myAppModule.controller('TextController', function ($scope) {
            $scope.lists = JSON.parse('[{"user_name": "Pranav", "user_id": 1}, {"user_name": "Sagar", "user_id": 2}]');
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.