agon024 agon024 - 4 months ago 14
jQuery Question

angularJS - Unable to load API Json response data into my HTML file

Here is the code that I am using:

angular.module('ngApp', [])
.factory('authInterceptor', authInterceptor)
.constant('API', 'http://myserver.com/app/api')
.controller('task', taskData)

function taskData($scope, $http, API) {
$http.get( API + '/tasks' ).
success(function(data) {
$scope.mainTask = data;
console.log(data);
});
}


Here is my HTML file:

<html>

<head>
<title>PCC ECAR App</title>

<link href="../app.css" rel="stylesheet" />
</head>

<body ng-app="ngApp" ng-controller="task" class="">

<div class="view1"> {{mainTask.Amount} </div>

<!-- Third Party Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

<!-- Main App Script -->
<script src="../app/app.js"></script>

</body>
</html>


Here is a screenshot of the console log from the API response:

enter image description here

What is happening is when you go to the page, the element
view1
will show
{{mainTask.Amount}}
for a half a second and then disappear leaving the element blank. I am obviously doing something wrong. Why cant I load the data into the HTML?

Answer

The /Tasks endpoint is returning an array of tasks. You would need to do:

$scope.mainTask = data.Tasks[0];

Or use ng-repeat to loop through the tasks:

<div class="view1" ng-repeat="task in mainTask.Tasks"> {{task.Amount} </div>