user2726041 user2726041 - 1 day ago 4
AngularJS Question

Retrieve json data in Angular controller

I'd like to get a couple of values out of a JSON file in my app controller.

I have a JSON file that looks something like this:

{
"login": [
{
"username": "admin",
"password": "admin"
}
],
"header": [
{
"subTitle": "Hello",
"color": "red"
}
]
}


I am attempting to retrieve a value like this:

app.controller('loginCtrl', function($http, $scope) {
data = $http.get('data.json');
console.log(data.login.username);
}


However, all I'm getting in the console is
TypeError: Cannot read property 'username' of undefined
.

Answer
data = $http.get('data.json');
data.then(function(result){
    console.log(result.login[0].username);
});
Comments