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

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:
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?

$scope.mainTask.tasks is an array that has your tasks data. You can loop through it in the view:
<ul>
<li ng-repeat="task in mainTask.tasks">{{task.Amount}}</li>
</ul>

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>

Related

Why is AngularJS printing "> " in ng-repeat

I am trying to get AngularJS to parse all the data given to it in JSON from a Spring rest controller. I am able to get the data to parse and everything but whenever angular repeats in the loop it print a text of "> " on the page.
My javascript
var HOST_SERVER = "http://localhost:8080";
angular.module('exchange', [])
.controller("Book", function ($scope, $http) {
$http.get(HOST_SERVER + "/exchange/get")
.then(function (response) {
$scope.books = response.data;
});
});
The html
<!DOCTYPE html>
<html data-ng-app="exchange">
<head>
<title>The Book Exchange</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="jsengine01.js"></script>
<meta charset="utf-8" />
</head>
<body>
<!-- test stuff-->
<div data-ng-controller="Book">
<div data-ng-repeat="book in books">>
<h1>{{book.title}}</h1>
<h4>By {{book.author}}</h4>
</div>
</div>
</body>
</html>
I tested the controllers and they return the appropriate json responses but I can post those as well if it would be helpful
There is a second > in your code that is being repeated...
<body>
<!-- test stuff-->
<div data-ng-controller="Book">
<div data-ng-repeat="book in books">> <!-- Remove the second '>' -->
<h1>{{book.title}}</h1>
<h4>By {{book.author}}</h4>
</div>
</div>
</body>

How to display data in HTML from http get call using angularJS 1.6

I am able to console the result of the http call but when I bind it so that I can view on the html page I am unable to do it. Can someone help me with this? I am posting the controller code and the html below.
Controller code
//module
var weatherApp = angular.module('weatherApp',['ngRoute' , 'ngResource']);
//Routes
//http://api.openweathermap.org/data/2.5/forecast/daily?APPID=metric
weatherApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl:'pages/home.htm',
controller:'homeController'
})
.when('/forecast', {
templateUrl:'pages/forecast.htm',
controller:'forecastController'
});
});
//services
weatherApp.service('cityService' ,function() {
this.city ="San Jose, CA";
});
//controllers
weatherApp.controller('homeController' ,['$scope', 'cityService', function($scope , cityService) {
$scope.city = cityService.city;
$scope.$watch('city' , function () {
cityService.city = $scope.city;
});
}]);
$scope.city = cityService.city;
console.log($scope.city);
$http({
url: "http://api.openweathermap.org/data/2.5/forecast/daily?APPID==metric",
method: "GET",
params: {q: $scope.city, cnt:2}
}).then(function(response){
$scope.weatherResults = response.data;
console.log($scope.weatherResults);
});
}]);
HTML CODE For Index.htm
<!DOCTYPE html>
<html lang="en" ng-app="weatherApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/navbar.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-resource.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<!-- NAVBAR -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<a class="navbar-brand" href="#">Accurate Weather</a>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>Home</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- NAVBAR ENDS-->
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
Code for Forecast.html
Forecast for {{city}} <!-- THIS WORKS -->
{{ weatherResult.cnt }} <!-- THIS DOES NOT WORK -->
Code for home.htm (EVERYTHING WORKS FINE HERE JUST POSTING FOR THE SAKE OF CLARITY)
<div class = "row">
<div class = "col-md-6 col-md-offset-3">
<h4>Forecast by city</h4>
<div class="form-group">
<input type="text" ng-model="city" class="form-control" />
</div>
Get forecast
</div>
</div>
console output correctly displays the objects:
Maybe try and initialize $scope.weatherResult as an empty object in your controller so that AngularJS can watch it correctly.
Just put this assigning inside $scope.apply to notify angular engine that data was changes asynchronously so it should be processed correctly
$scope.$apply(function () {
$scope.weatherResult = response.data; //IF I LOG THIS IT WORKS
});
Also good to add check that gigest cycle is not in progress now
if(!$scope.$$phase) {
//$digest or $apply
}
Angular's inbuilt 2-way data binding does not work on http responses which is a known issue. Use $timeout to manually kick in the 2-way data binding and thereby initiating the digest cycle.
$scope.getWeather= function(){
$http({
url: "http://api.openweathermap.org/data/2.5/forecast/daily?AP&units=metric",
method: "GET",
params: {q: $scope.city, cnt:2}
})
.then(function(response){
$timeout(function(){
$scope.weatherResult = response.data;
}, 0);
});
}
}]);
Note the $timeout timer is set at 0ms to immediately kick in the digest cycle.
Correct Code posted. I was assigning the http get call to $scope.variable, I just removed it and it started working. Thanks

AngularJS $HTTP.json

I'm trying to pull the list of current streams from the API and iterate that information with AngularJS. When I put in the JSON data directly in the js file, Angular works fine. However, when using an http request as shown below, I get a blank page. I've searched high and low, but have had trouble applying it to my specific issue. Any help is appreciated. Thanks!
Http file:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.game }}
</li>
</ul>
</div>
<script src="repeat.js"></script>
</body>
</html>
Repeat.js
var app = angular.module('myApp', []);
app.controller('namesCtrl', function($scope, $http) {
$http.jsonp("https://api.twitch.tv/kraken/streams?json_callback=JSON_CALLBACK")
.success(function(response) {$scope.names = response.streams;});
});
https://api.twitch.tv/kraken/streams?json_callback=JSON_CALLBACK isn't JSONP (it is plain JSON).
You need a server that will make a JSONP response in order to use $http.jsonp().
Well, using $http.get('url') does work. I was incorrectly thinking the 'data' object was an array and passing "[0]" to it which was incorrect. Below is the code and it works to pull the info and repeat the data as indicated in the markup. Thanks for your help!
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in data.streams">
{{ x.game }}
</li>
</ul>
</div>
<script src="repeat.js"></script>
</body>
</html>
JS:
var app = angular.module('myApp', []);
app.controller('namesCtrl', function($scope, $http) {
$http.get('https://api.twitch.tv/kraken/streams?').success(
function(data, status){
$scope.data = data;
});
});

How to get angular app to access backend-API

So, Ive made a backend API for a todo-app Im working on, I know that http://localhost:3000/api/todo/done is working and returns two objects, looking like this:
[{"_id":"54d6485357a52fc640bb3814","text":"Hämta tårta","completed":true},{"_id":"54d648ae57a52fc640bb3815","text":"Köpa dricka till Antons kalas","completed":true}]
Ive now written a first attempt at a frontend in angular. It all runs well in node, with no errors but I do not get any todos listed in my todo-list div. Can you please advise on this?
HTML:
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
<script src="../javascripts/core.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</script>
</head>
<body ng-controller"mainController">
<div class="container">
<!-- HEADER AND TODO COUNT -->
<div class="jumbotron text-center">
<h1>I'm a Todo-aholic <span class="label label-info">{{ todos.length }}</span></h1>
</div>
<!-- TODO LIST -->
<div id="todo-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- LOOP OVER THE TODOS IN $scope.todos -->
<div class="checkbox" ng-repeat="todo in todos">
<label>
<input type="checkbox" ng-click="deleteTodo(todo._id)"> {{ todo.text }}
</label>
</div>
</div>
</div>
</body>
</html>
ANGULAR CODE:
var nodeTodo = angular.module('node-todo', []);
function mainController($scope, $http) {
$scope.formData = {};
// when landing on the page, get all todos and show them
$http.get('/api/todo/done')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}
I dont even get anything printed in the console and I dont understand why...
Check if your angular app is correctly wired up. I don't see an ng-app directive in your html snippet and there is probably a typo in ng-contoller="mainController" (= is missing). Also your controller is not registered with module (but in this case it shouldn't make any difference).
Here is JSFiddle that at least shows error message when requesting data. Hope this helps to solve your problem
Try this in the html (note the ng-app atribute) to reference your module.
<body ng-app="node-todo">
<div class="container" ng-controller="mainController">
and then connect your controller to your app/module like this:
var nodeTodo = angular.module('node-todo', []);
nodeTodo.controller('mainController',
['$scope', '$http', function($scope, $http){
$scope.formData = {};
// when landing on the page, get all todos and show them
$http.get('/api/todo/done')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}]);
Hope this helps.

Restify server with Angular, not working

I am learning to use Restify to build a Restful API and work with Angular.
Below is my structure:
Project
page_admin
core.js
index.html
node_modules
restify
mongojs
server.js
I had set up server and implemented several API calls.
Below news API return a list of JSON data in browser:
`http://localhost:8080/news`
`[{"_id":"53b2a2c3373551813dfe8b91","title":"first","subtitle":"foobar","textbody":"","postedOn":"2014-07-01T12:00:03.215Z"},{"_id":"53b2a122373551813dfe8b8e","title":"my second","subtitle":"my second title","textbody":"node is cool","postedOn":"2014-07-01T11:53:06.389Z"},{"_id":"53b2a0cd373551813dfe8b8d","title":"delay announcement","subtitle":"sub ","textbody":"I am the text body","postedOn":"2014-07-01T11:51:41.678Z"}]`
here is my code to handle client side route:
server.get('/', restify.serveStatic({
'directory': './page_admin',
'default': 'index.html'
}));
My index.html is simple:
<!-- index.html -->
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="bluesky">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>My test app</title>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
html { overflow-y:scroll; }
body { padding-top:50px; }
#todo-list { margin-bottom:30px; }
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
<script src="core.js"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL TODOS -->
<body ng-controller="mainController">
<div class="container">
<!-- HEADER AND TODO COUNT -->
<div class="jumbotron text-center">
<h1>My example is working <span class="label label-info">{{ news.length }}</span></h1>
</div>
<!-- TODO LIST -->
<div id="todo-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- LOOP OVER THE TODOS IN $scope.todos -->
<div class="checkbox" ng-repeat="new in news">
<label>
<input type="checkbox" ng-click="deleteTodo(new._id)"> {{ new.subtitle }}
</label>
</div>
</div>
</div>
</div>
</body>
</html>
core.js is like this:
var bluesky = angular.module('bluesky', []);
function mainController($scope, $http) {
$scope.formData = {};
$http.get('/news')
.success(function(data) {
$scope.news = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}
when I try to navigate to: http://localhost:8080
I got my index page but it shows me:
'My example is working {{ news.length }}
and in console, I saw following error:
GET `http://localhost:8080/core.js` 404 (Not Found)
localhost/:24
Uncaught Error: No module: bluesky
angular.min.js:18
what I just missed so that the angular is not retrieving the data?
=============================================================
upate
if I directly include core.js put code inside , then it works.
but, how to solve this 404 not found issue? just don't want to include all js files in the index page.
As far as my knowledge about angular js, controller is not defined in your module. So instead of using function mainController($scope, $http) {
....
}
you should define controller inside the module bluesky as follows
bluesky.controller("mainController",function($scope,$http)
{
....
});

Categories

Resources