Restify server with Angular, not working - javascript

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

Related

Unable to pass form data using Angular.js

I am new to Angular.js and am trying to send form data to the server but I am getting an error for angular.js:13424 Error: [ng:areq]. I did try many answers available on Stack Overflow but I am not able to find the answer for my problem.
index.view.html (for register)
<div class="col-md-6 col-md-offset-3" >
<input type="text" ng-model="fname" placeholder="Enter the name :"required >Fristname
<br> <br>
button type="button" class="btn btn-success navbar-btn" ng-click=register()>Register </button>
</div>
index.controller.js
(function ()
{
angular
.module('app')
.controller('register.IndexController', function($scope,$http)
{
$scope.register= function()
{
$http.post('http://localhost:9000/user/register', {firstName : $scope.fname}).success(function(response)
{ console.log($scope.fname);
})
}
})
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS JWT Authentication Example & Tutorial</title>
<!-- bootstrap css -->
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!-- application css -->
<link href="app-content/app.css" rel="stylesheet" />
</head>
<!-- HEADER AND NAVBAR -->
<header>
<nav class="navbar navbar-default">
<nav class="cf" ng-include="'nav/index.view.html'" ng-controller="Main.IndexController"></nav>
</nav>
</header>
Seems that you are using the wrong controller identifier while processing your request.
You have named your controller as register.IndexController, but from the html , you are trying to access it as Main.IndexController.
Please check whether changing the html controller idenentifier solves your problem.
If you plan on using nested controllers, you can do that also. But the scope has to be identified correctly whichever controller you are using.

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>

Impress.js and AngularJS Controller

I am running an AngularJS application/controller. My goal is to initialize and use the impress.js library on a page that is being dynamically loaded into my main home page. However, when I try to initialize the library, the page does not load. Attached is a snippet of the controller and html file.
NOTE: When I print the impress() object to the console, it is not null, and has the required functions. It is my suspicion that the impress() object is not hooking up to the page correctly.
Controller:
'use strict';
// Create the angular module
var cmodule = angular.module('coverage', ['ngRoute'])
// Create the coverage controller
cmodule.controller('coverageController', function($scope) {
console.log("Entering controller");
function require(script) {
$.ajax({
url: script,
dataType: "script",
async: true, // <-- This is the key
success: function () {
console.log(impress());
impress().init();
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
console.log("About to require");
angular.element(document).ready(function () {
require("/content/libraries/impress.js");
});
});
HTML File:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=1024" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>My Coverage</title>
<link rel="stylesheet" href="/content/styles/team1.css">
</head>
<body class="impress-not-supported">
<!--
For example this fallback message is only visible when there is `impress-not-supported` class on body.
-->
<div class="fallback-message">
<p>Your browser <b>doesn't support the features required</b> by impress.js, so you are presented with a simplified version of this presentation.</p>
<p>For the best experience please use the latest <b>Chrome</b>, <b>Safari</b> or <b>Firefox</b> browser.</p>
</div>
<!-- Now the fun begins -->
<div id="impress">
<!-- The background image -->
<div class="present" data-x="0" data-y="0">
<!-- Place Image here -->
</div>
<!-- Example content -->
<div id="url-ident" class="step" data-x="0" data-y="0">
<q>Ready to view your coverage?</q>
</div>
<!-- Example content -->
<div id="step1" class="step" data-x="500" data-y="0">
<p>Questions start here!</p>
</div>
</div> <!-- /div impress -->
<script type="text/javascript" src="/content/libraries/impress.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!--script type="text/javascript">impress().init();</script-->
</body>
</html>
This problem was fixed by using the jmpress.js library instead, found here.

NgRoute not loading (modulerr error)

I'm going through Scotch.io's MEAN Machine book, and I'm nearly done. Problem is I can't get my Angular code to run correctly——even when I'm literally copying the code from their Github. Whenever I open my app on localhost, ngRoute fails to load (or be injected or whatever) correctly.
Here is my code:
App.js
angular.module('userApp', ['ngAnimate', 'app.routes', 'authService', 'mainCtrl', 'userCtrl', 'userService'])
]);
App.routes
angular.module('app.routes', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
//home page route
.when('/', {
templateUrl : 'app/views/pages/home.html'
})
//route for the login page
.when('/login', {
templateUrl : 'app/views/pages/login.html',
controller : 'mainController',
controllerAs : 'login'
});
//get rid of the hash in the URL (url prettification)
$locationProvider.html5Mode(true);
});
mainCtrl.js
angular.module('mainCtrl', [])
.controller('mainController', function($rootScope, $location, Auth) {
var vm = this;
//get user info if logged in
vm.loggedIn = Auth.isLoggedIn();
//check to see if user is logged in ON EVERY REQUEST
$rootScope.$on('$routeChangeStart', function() {
vm.loggedIn = Auth.isLoggedIn();
//get user information on route change
Auth.getUser()
.success(function(data) {
vm.user = data;
});
});
//this function handles the login form
vm.doLogin = function() {
vm.processing = true;
//call the Auth.login() function
Auth.login(vm.loginData.userName, vm.loginData.password)
.success(function(data) {
vm.processing = false;
//if user is logged in, redirect to user page
$location.path('/users');
});
};
//function to handle logging out
vm.doLogout = function() {
Auth.logout();
//reset ALL user info
vm.user = {};
$location.path('/login');
};
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User CRM</title>
<!-- FOR ANGULAR ROUTING -->
<base href="/">
<!-- CSS -->
<!-- load bootstrap from CDN and custom CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.1/paper/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<!-- JS -->
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-animate.js"></script>
<!-- controllers -->
<script src="app/controllers/mainCtrl.js"></script>
<script src="app/controllers/userCtrl.js"></script>
<!-- services -->
<script src="app/services/authService.js"></script>
<script src="app/services/userService.js"></script>
<!-- main Angular app files -->
<script src="app/app.routes.js"></script>
<script src="app/app.js"></script>
</head>
<body ng-app="userApp" ng-controller="mainController as main">
<!-- NAVBAR -->
<header>
<div class="navbar navbar-inverse" ng-if="main.loggedIn">
<div class="container">
<div class="navbar-header">
<span class="glyphicon glyphicon-fire text-danger"></span> User CRM
</div>
<ul class="nav navbar-nav">
<li><span class="glyphicon glyphicon-user"></span> Users</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-if="!main.loggedIn">Login</li>
<li ng-if="main.loggedIn" class="navbar-text">Hello {{ main.user.username }}!</li>
<li ng-if="main.loggedIn">Logout</li>
</ul>
</div>
</div>
</header>
<main class="container">
<!-- ANGULAR VIEWS -->
<div ng-view></div>
</main>
</body>
</html>
This is the exact error I'm receiving:
https://docs.angularjs.org/error/$injector/modulerr?p0=userApp&p1=Error: [$injector:nomod] http://errors.angularjs.org/1.3.8/$injector/nomod?p0=userApp
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:6:416
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:21:366
at a (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:21:7)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:21:250
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:35:424
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:7:302)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:35:202)
at Ob (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:38:435)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:17:350
Remove 'userCtrl' from the dependencies in the userApp module in app.js. You may have created that file, but there probably isn't any content. This should do the trick.
I ran into the same problem, the 'userService' dependency in app.js isn't loaded in the index.html file.
To fix this issue add the userService.js file in your index.html file underneath the authService.js file like so:
<!-- services -->
<script src="app/services/authService.js"></script>
<script src="app/services/userService.js"></script>
In your index.html => <body ng-app="userApp" so you need add to your mainCtrl.js look like this:
angular.module('userApp.mainCtrl', [])
You also need do the same way to userCtrl.js, authService.js, userService.js and app.routes.js.
Now in your App.js finally may look like this:
angular.module('userApp', ['ngAnimate', 'userApp.Routes', 'userApp.authService', 'userApp.mainCtrl', 'userApp.userCtrl', 'userApp.userService'])
]);
Edit
I try your code in plunker but with commenting <base href="/"> and change
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
for it work in plunker. Here (http://embed.plnkr.co/BHyE6iWDN5uXqiitaMDU/preview) you can visit it with same error in console log. It's seem due to fail load some depedencies which i left empty at some file.
Here (http://embed.plnkr.co/eD4TYgMNq4MDHQZ7p3n0/preview) another plunker that you can see the error has gone, all of depedencies success loaded. Make sure you have correct typo & not missing the depedencies.

Invalid characters and modules when translating a node.js app from javascript to coffee script

So basically I'm trying to follow the tutorial listed here, except using coffee script instead of javascript. I'm getting two errors on the website, 1. A syntax error regarding the '#' character in the first line of core.coffee (# public/core.coffee) 2. an error that says no module: scotchTodo.
On the actual page, instead of showing the number of todos and each todo, it says
{{ todos.length }} and {{ todo.text }}.
Here's my core.coffee:
# public/core.coffee
scotchTodo = angular.module 'scotchTodo', []
mainController = ($scope, $http) ->
$scope.formData = {}
# when landing on the page, get all todos and show them
$http.get '/api/todos'
.success((data) ->
$scope.todos = data
console.log data
).error((data) ->
console.log 'Error: ' + data
)
# when submitting the add form, send the text to the node API
$scope.createTodo = ->
$http.post '/api/todos', $scope.formData
.success((data) ->
$scope.formData = {} # clear the form so our user is ready to enter another
$scope.todos = data
console.log data
).error((data) ->
console.log 'Error: ' + data
)
# delete a todo after checking it
$scope.deleteTodo = (id) ->
$http.delete '/api/todos/' + id
.success((data) ->
$scope.todos = data
console.log data
).error((data) ->
console.log 'Error: ' + data
)
Here's my index.html:
<!-- index.html -->
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="scotchTodo">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Todo 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.coffee"></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>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>
<!-- FORM TO CREATE TODOS -->
<div id="todo-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- BIND THIS VALUE TO formData.text IN ANGULAR -->
<input type="text" class="form-control input-lg text-center" placeholder="I want to buy a puppy that will love me forever" ng-model="formData.text">
</div>
<!-- createToDo() WILL CREATE NEW TODOS -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
</form>
</div>
</div>
</div>
</body>
</html>
Please let me know if you need anything else from me, really trying to understand what's going on. Thanks!
You seem to be trying to use CoffeeScript in the browser:
<script src="core.coffee"></script>
You need to either compile it first, or ad the compiler to your browser code so it can be compiled on the fly. The latter is generally not a good idea, so you should add a build step that uses the CoffeeScript compiler to turn your core.coffee into core.js, then include that script in your index.html.
From the terminal that would look something like coffee -c core.coffee, but there are more options as can be seen here.

Categories

Resources