How to get angular app to access backend-API - javascript

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.

Related

Angular Submit Syntax and message if no results found using MovieDB API

I'm super new at web development and am trying to learn how to use Angular for a mini project. I'm using The MovieDB's restful API's and all I want to do is a simple search for a movie title, return results that are found, and return a message if nothing is found.
Unfortunately I'm hitting a few comprehension hurdles and I have looked for a solution but haven't found one that matches what I'm doing, which I think is pretty simple (most of the ones I've seen are for more complex approaches and I think it's just beyond my understanding for the moment)
All I want to do right now is have a searchbar, a user types in a movie name, clicks submit, and the angular app will return results. But I can't quite figure out how to pass the submit through to my app. Here is my html code:
<!doctype html>
<html>
<head>
<link
href="http://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css"
rel="stylesheet" />
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js">
</script>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<link href="css/main.css" rel="stylesheet" />
</head>
<body ng-app="myApp">
<div class="header">
<img src="img\logo.png"
style="width: 80px; height: 80px;>
<div class="container">
<h1>The MovieDB Search Tool</h1>
<h2>Search for a movie!</h2>
</div>
<div class="main" ng-controller='MainController'>
<div class="searchbar">
<form ng-submit="submitFunction(field)">
<input type="text" name="field" placeholder="Search for a
movie">
<input type="submit" value="Submit">
</form>
</div>
<div class="container">
<div ng-repeat="details in movieList" class="col-md-6">
<div class="thumbnail">
<img ng-
src="https://image.tmdb.org/t/p/w154{{details.poster_path}}">
<p>{{ details.title }}</p>
<p class="date">Release Date: {{ details.release_date | date
}}</p>
<p>{{details.overview}}</p>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container"></div>
</div>
</body>
</html>
And my javascript code for the angular app:
app.controller('MainController', ['$scope', '$http', function($scope, $http) {
$scope.movieTitle = function submitFunction(field){
}
$http.get('https://api.themoviedb.org/3/search/movie?api_key='+api_key+'&language=en-US&query='
+$scope.movieTitle+'&page=1&include_adult=false')
.then(successCallback, errorCallback);
function successCallback(response){
$scope.movieList = response.data.results
}
function errorCallback(error){
}
}]);
If I plug in a movie name like 'Deadpool' the html works just fine, of course with a static value it runs automatically. And I need it to work on submit, and the way I'm trying isn't working. I would think I need to get a variable passed in to the $scope, buy the submit function but I'm not getting anything when I run this.
If I could get to this point, I think I could figure out the logic to display a message of no results found, it should be as simple as checking the json object the api returns and looking at the "total results" number, then returning a specific message (at least I hope it's that simple).
Any and all help is appreciated!
HTML:
<form ng-submit="submitFunction()">
<input type="text" ng-model="movieTitle" placeholder="Search for a
movie">
<input type="submit" value="Submit">
</form>
CONTROLLER:
app.controller('MainController', ['$scope', '$http', function($scope, $http) {
$scope.submitFunction = function(){
$http.get('https://api.themoviedb.org/3/search/movie?api_key='+api_key+'&language=en-US&query='+$scope.movieTitle+'&page=1&include_adult=false')
.then(successCallback, errorCallback);
}
function successCallback(response){
$scope.movieList = response.data.results
}
function errorCallback(error){
}
}]);

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

console.log for $scope in angular js

Why I'm not able to console output $scope values ? I'm trying to extract user assigned values from the pages and retrieve in controller. Eventually i would like to pass this to service so multiple controllers can access these data.
HTML
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<link rel="stylesheet" href="css/bootstrap.min.css" />
<!-- CDN lib files -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.1.0/ui-bootstrap-tpls.min.js"></script>
<!-- custom angular script -->
<script src="js/app.js"></script>
</head>
<body>
<div class="container">
<div ng-controller="mainController">
<h1>Hello world!</h1>
<label> Please enter something</label>
<input textarea ng-model="name"></input>
<h4> This is what you entered : {{ name }} </h4>
<h4 style=color:red> now filtering: {{ lower() }}</h4>
</div>
</div>
</body>
</html>
APP.JS
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) {
$scope.name = 'Test ';
$scope.lower = function(){
return $filter('lowercase')($scope.name);
}
$scope.name = $scope.lower();
console.log($scope.name);
console.log($scope.lower());
}]);
Console will output values upon initializing but not after user make changes.
You need to watch the scope variable:
$scope.$watch('name', function() {
console.log($scope.name);
});
More information: https://stackoverflow.com/a/15113029/5787736
Just a more "functional" version. Everyone is right, you are logging the observable, not what was observed. What you want is for console.log to be called on each change to $scope, not called once (as you have it now).
$scope.$watch("name", console.log);
You're logging only from the constructor. If you want to log each time something changes, consider a watch:
$scope.$watch("name", function() {
console.log($scope.name);
}
Why would you expect a controller to be rerendered when a scope variable changes? You can use scope watchers or input event listeners to listen for changes.
Here's an example with a watcher:
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) {
$scope.name = 'Test ';
$scope.lower = function(){
return $filter('lowercase')($scope.name);
}
$scope.name = $scope.lower();
console.log($scope.name);
console.log($scope.lower());
$scope.$watch('name', function() {
console.log($scope.name);
console.log($scope.lower());
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" class="container">
<div ng-controller="mainController">
<h1>Hello world!</h1>
<label>Please enter something</label>
<input textarea ng-model="name" />
<h4> This is what you entered : {{ name }} </h4>
<h4 style=color:red> now filtering: {{ lower() }}</h4>
</div>
</div>

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)
{
....
});

Why is my Angular.js $routeProvider doing nothing?

I'm learning Angular.js right now by following along with the videos at Egghead.io. I'm at the $routeProvider video, and my app isn't routing at all.
It's ultra basic, here's the script (app.js):
var app = angular.module('myApp', []);
// routes
app.config(function ($routeProvider) {
$routeProvider.when('/pizza', { template: 'Yum!!' });
});
app.controller('FirstCtrl', function ($scope) {
$scope.data = { message: "Hello" };
});
And the html:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
{{data.message + " world"}}
</div>
</div>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.3/angular.min.js"></script>
<script src="app.js"></script>
From my understanding, http://host/#/pizza should simply show "Yum!!" since I'm passing a string in the template. It doesn't appear to do anything though, I still get "Hello world" as evaluated by the FirstCtrl.
Why isn't the $routeProvider doing anything in my app?
You need to put an ng-view element in where you want the routeProvider to stick the page's template.
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
{{data.message + " world"}}
<ng-view></ng-view>
</div>
</div>
Note that indicating it like below keeps you cross-browser compliant.
<div ng-view> </div>
or, for that matter:
<ANY ng-view> </ANY>
More information is available here:
http://docs.angularjs.org/api/ng.directive:ngView

Categories

Resources