IAmAkittycatAMA IAmAkittycatAMA - 8 months ago 36
Javascript Question

AngularJS get request not returning data

I Have the following code in which I'm trying to get a

file and attach its contents to my $scope.

The first
returns the result that I need, but the second returns

What would be the correct way to write this so that the data is stored?

'use strict';

var myApp = angular.module('myApp.view1', ['ngRoute']);

myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'

myApp.controller('View1Ctrl', [


function($scope, $http) {
$scope.data = res.data.info



The reason for this is with something called Promises. I definitely suggets looking into them. Here is kind of what happens in order:


That tells javascript I want to get the JSON data. But it does not actually get it yet. Then, it does that console log.


Well $scope.data is undefined. Nothing has set it yet! Then, javascript actually gets the JSON data. When it gets the data, the function within the then is called. After this,

$scope.data = res.data.info

$scope.data is defined, which is why this console.log works. Read more about promises for more info!

Here is a good starting point: https://www.youtube.com/watch?v=wA0gZnBI8i4