Expressjs - Angular loading not loading index page - angularjs

I'm having issue developing an application using expressjs and angular. I'm loading angular, bootstrap etc from my index page. to test, I put a button <a ui-sref=about>about</a> to go to about page. when I click the button from my index page, no problem. the page loads along with the libraries used in index.html and it console logs a message from AboutController. However, when I refresh the page http://localhost:3000/about, the page loads without loading the angular, bootstrap etc libraries. I know my <script> tags that load the those files are in index.html but I wonder if there is a way refresh the page from http://localhost:3000/about and load index first, then it would go to about or if my app could load the files in index on refresh making available the same files to about .
here is my file structure
Here is my code:
Index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<base href="/">
</head>
<body>
<li><a ui-sref="about">About</a></li>
<li><a ui-sref="home">Home</a></li>
<ui-view></ui-view>
</body>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script src="lib/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="lib/angular/angular.min.js" type="text/javascript"></script>
<script src="lib/angular/angular-ui-router.js" type="text/javascript"></script>
<script src="lib/angular/angular-animate.js" type="text/javascript"></script>
<script src="lib/angular/anim-in-out.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
<script src="controllers/HomeController.js" type="text/javascript"></script>
<script src="controllers/AboutController.js" type="text/javascript"></script>
</html>
Server.js
/**
* Created by carlosgonzalez on 4/14/17.
*/
/**
* Created by carlosgonzalez on 4/14/17.
*/
var express = require('express');
var app = express();
var path = require('path');
var PORT = process.env.PORT || 3000;
// app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(__dirname + '/public'));
app.get('/', function (req,res,next) {
res.sendFile('index.html');
})
app.get('/about', function (req,res) {
res.sendFile(__dirname+'/public/partials/about.html');
})
app.listen(PORT, function () {
console.log("Server running in PORT " + PORT);
});
main.js
/**
* Created by carlosgonzalez on 4/5/17.
*/
var myApp = angular.module('myApp',['ui.router']);
console.log("in myApp");
myApp.config( function ($stateProvider, $locationProvider) {
$stateProvider
.state('home',{
url:'/home',
templateUrl:'/partials/home.html',
controller:'HomeController'
})
.state('about',{
url:'/about',
templateUrl:'/partials/about.html',
controller:'AboutController'
})
$locationProvider.html5Mode(true).hashPrefix('/#!/');
// $locationProvider.html5Mode(true);
})
// /test.html#!/about
AboutController.js
/**
* Created by carlosgonzalez on 4/14/17.
*/
/**
* Created by carlosgonzalez on 4/5/17.
*/
myApp.controller('AboutController',['$scope','$rootScope', '$rootScope', '$scope',
function($rootScope, $scope) {
console.log("Hello from about controller");
$scope.hello = 'about';
}]);/**
* Created by carlosgonzalez on 4/14/17.
*/
about.html
<div>{{hello}}</div>

You need to change your server.js to make it renders the index.html.
app.get('/about', function (req,res) {
res.sendFile('index.html');
})
Once index.html is rendered ui-router will trigger the in-browser routing and display your about page correctly.

Related

controller is not working with route functionality

I am new in angularjs tech. I have implemented one registration function in my project.
I have created one js file for routing and controller functionality in my project and its working fine, If i will do separate router and controller file then I am application is failing.
I need to do separate file for the router and controller.
Below is my code in one file.
app.js file
var app = angular.module('crasApp', [ 'ngRoute' ]);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : "./views/xyz.html",
controller : "searchCtrl"
}).when("/registration", {
templateUrl : "./views/abc.html",
controller : "MainCtrl"
}).when("/view", {
templateUrl : "./views/viewsdata.html",
controller : "overViewCtrl"
});
});
app
.controller(
"MainCtrl",
function($scope, $http) {
console.log("Hi");
});
index.html
<!DOCTYPE html>
<html ng-app="crasApp">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<head>
<!-- Use Bootstrap -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/abn-stylesheet.css">
<link rel="stylesheet" href="./css/style.css">
<script src="./javascripts/jquery/jquery-1.12.4.js"></script>
<script src="./javascripts/jquery/jquery.min-1.12.4.js"></script>
<script src="./javascripts/angular/bootstrap.min.js"></script>
<!-- <script src="./javascripts/angular/angular.min.js"></script> -->
<script src="./javascripts/controllers/app.js"></script>
<!-- <script src="./javascripts/angular/angular-route.js"></script> -->
<script src="./javascripts/router/router.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
</head>
<div ng-view></div>
</html>
xyz.html
<!DOCTYPE html>
<html ng-app="crasApp">
<head>
<!-- Use Bootstrap -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/abn-stylesheet.css">
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/ngDatepicker.css">
<script src="./javascripts/jquery/jquery-1.12.4.js"></script>
<script src="./javascripts/jquery/jquery.min-1.12.4.js"></script>
<script src="./javascripts/angular/bootstrap.min.js"></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> -->
<script src="./javascripts/controllers/app.js"></script>
</head>
<body ng-controller="MainCtrl">
Hi
</body>
<html>
So, Its working file if I am using one app.js file
I want to do seprate router and controller file.
router functionality i moved into different file and its working router functionality but not working controller functionality..
Separate router file as below.
router.js
var app = angular.module('crasApp', [ 'ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : "./views/retrieveTerminationReason.html",
/*controller : "searchCtrl"*/
}).when("/registration", {
templateUrl : "./views/registration.html",
/*controller : "MainCtrl"*/
}).when("/view", {
templateUrl : "./views/forbearanceRegistartionOverview.html",
/*controller : "overViewCtrl"*/
});
});
app.js as a controller
var app = angular.module('crasApp', []);
app
.controller(
'MainCtrl',
function($scope, $http) {
console.log("Hi");
});
Please any one can help on this part.
In router.js, change var app = angular.module('crasApp', [ 'ngRoute']) to var app = angular.module('crasApp').
Also, in app.js, your declaration should be: var app = angular.module('crasApp', ['ngRoute']);. Since you have a single module, 'crasApp', you must declare it's dependencies when you declare the module itself.
What you have currently is re-creating the module vs. appending functionality.
Also, be sure to include your router.js as well in your HTML .
the issue
when you're using var app = angular.module('crasApp', [ 'ngRoute']); in your route.js file you are initializing new module NOT adding config to existing module!
the best approach for structuring an Angular App is NOT using variable you can call your module in a different way like:
app.js
var MODULE_NAME = 'crasApp'
angular.module(MODULE_NAME, ['ngRoute']);
to create controller controllers.js
angular.module(MODULE_NAME).controller('MainCtrl',function($scope, $http) { //Note removing the dependencies array
console.log("Hi");
});
to create config routes.js
angular.module(MODULE_NAME).config(function($routeProvider) { //Note removing the dependencies array
$routeProvider.when("/", {
templateUrl : "./views/retrieveTerminationReason.html",
/*controller : "searchCtrl"*/
})
in your index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/routes.js"></script>
<script src="js/controllers.js"></script>
</head>
Note you don't need ng-controller directive in your HTML because defining it in routes is enough
separating services
create services.js for example
angular.module(MODULE_NAME).factory('Users',function($http,$q) {
return {
getUsers:function(){
var def = $q.defer();
$http({url:'URL_HERE',method:'GET'}).then(function(res){
def.resolve(res)
},function(err){
def.reject(err);
})
}
}
})
using in controller
angular.module(MODULE_NAME).controller('MainCtrl',function($scope, Users) { //Note Users is the name of the factory created above
Users.getUsers().then(function(res){
$scope.users=res;
},function(err){
$scope.error = err;
})
});

How to handle Express JS and Angular JS routes together?

I am working on a web application using Express, Angularjs. I have a main page (i.e index.html) that i want to serve on express. The code for the server is written in xpressServer.js.
// file tree
->controller
---formController.js
->js
---app.js
->node_modules
->views
---form.html
---home.html
-index.html
-package.json
-xpressServer.js
The above is the file structure of my application.
// xpressServer.js
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, '/js')));
app.use(express.static(path.join(__dirname, '/controller')));
app.use(express.static(path.join(__dirname, '/views')));
app.get('/', function(req,res) {
res.sendFile(path.join(__dirname + '/public/assets/view/index.html'));
});
app.listen(8081, function() {
console.log('listenin on port 8081');
});
And, my index.html is
// index.html
<!DOCTYPE html>
<html ng-app="formModule">
<head>
<base href="/" />
<title>dfgadfggth</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
</head>
<body>
<div ng-view></div>
<script type="text/javascript" src="/js/app.js"></script>
</body>
</html>
what exactly do i want to do?
I want to serve the index.html using Express routing and then route using angularjs.<div ng-view></div>.I want to grab a view depending on the route and then place it in ng-view present in the index.html.
The code for the app.js that handles angular routing is:
// app.js
'use strict';
var app = angular.module("formModule",['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/home', {
templateUrl: '/views/home.html'
})
.when('/form', {
templateUrl: '/views/form.html',
controller: '/controller/formController.js'
})
.otherwise({
redirectTo: '/home'
});
}]);
I have been searching for the solution but couldn't find one that worked for me. Kindly help me with this issue.
Thanks in advance!!

AngularJs routing is failing

My Index.html
<!doctype html>
<html data-ng-app="hotelApp">
<head>
<title>SRK Hotel</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="stylesheet" href="stylesheets/style.css"> -->
<!-- Angular dependencies -->
<link rel="stylesheet" type="text/css" href="lib/angular-material/angular-material.css">
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular-animate/angular-animate.min.js"></script>
<script src="lib/angular-aria/angular-aria.min.js"></script>
<script src="lib/angular-material/angular-material.min.js"></script>
<script src="lib/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="scripts/start.js" type="text/javascript"></script>
<script src="scripts/home-page-ctrl.js" type="text/javascript"></script>
<script src="scripts/states/misc-states.js" type="text/javascript"></script>
</head>
<body>
<!-- <div data-ng-include="'views/welcome-page.html'"></div> -->
<div ui-view="welcome"></div>
</body>
</html>
My app.js
(function() {
angular.module('hotelApp.controller', []);
angular.module('hotelApp.states', ['ui.router']);
angular.module('hotelApp', ['ui.router']);
})();
My states.js - that is there for declaration of states
angular.module('hotelApp.states')
.config(function ($stateProvider, $urlRouterProvider) {
'use strict';
$stateProvider
.state('hotelApp.homePage', {
url: '/home',
views: {
'welcome': {
templateUrl: 'views/welcome-page.html',
conntroller: 'homePageCtrl'
}
}
});
$urlRouterProvider.when('/', function($state){
console.log('$state ' , $state);
$state.go('hotelApp.homePage');
});
$urlRouterProvider.otherwise(function(){
console.log('hi');
});
});
my nodejs file
var express = require('express');
var cfenv = require('cfenv');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use('/lib', express.static(__dirname + '/node_modules'));
app.get('*', function(req, res) {
res.sendFile(__dirname+'/public/index.html');
});
var appEnv = cfenv.getAppEnv();
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("server starting on " + appEnv.url);
});
I am trying to use routing in this implementation but it is failing.
I have added this code but when i run my code.. nothing happens .. I just get a blank page. What is wrong with this implementation.? I get no error, no logs.
Your main module is defined as
angular.module('hotelApp', ['ui.router']);
So it depends exclusively on ui-router.
Your states are defined in a separate module, 'hotelApp.states', which is thus not part of your application.
Another problem is that the two JS files you've posted are app.js and states.js, and there is no <script> element in your html page for those two files. So the're not even loaded by the browser.

$http.get call app.get in Express

Code in server.js
var strava = require('node-strava-v3')
var express = require('express');
var app = express();
app.get('/', function(req, res){
strava.streams.activity({'id': 497191235, 'types':'distance'}, function(err, payload){
if(!err){
res.send(payload);
}
else{
res.send(err);
}
})
});
I would like to setup a view file (static HTML with a dynamic view) which gets its data via a controller file, which in turn retrieves it from the model (server.js) through app.get() call. I believe I would need to utilise $http.get() from the controller to access app.get()? The tutorials I read have provided a specifc path as the argument for $http.get(), but I don't think it applies to my situation.
Please advise - thank you.
[Edit] controller.js and index.html files at present:
//controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http',
function($scope, $http){
var refresh = function(){
$http.get('/').success(function(response){
$scope.contactlist = response;
});
};
refresh();
}]);
//index.html
<!DOCTYPE>
<html ng-app="myApp">
<head>
<title>Contact List App</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body>
<div class="container" ng-controller="AppCtrl">
<p>{{contactlist}}</p>
</div>
</body>
</html>

AngularJS Hello:{{test}} page not displaying?

Ok this is my first attempt at this. Trying to get my page to load. my App.js file has all the nessities I hope. here are my files below:
Index.html:
<!DOCTYPE html>
<html ng-app="TodoApp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/jquery-1.9.0.js"></script>
<script src="https://code.angularjs.org/1.3.5/angular-route.js"></script>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script src="Scripts/app.js"></script>
<link rel="stylesheet" type="text/css" href="Content/bootstrap.css" />
<title>Amazing Todo List</title>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
App.js:
var TodoApp = angular.module("TodoApp", ["ngResource", "ngRoute"]).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'list.html' }).
otherwise({ redirectTo: '/' });
});
var ListCtrl = function ($scope, $location) {
$scope.test = "testing";
};
List.html:
<h1>Hello: {{test}}</h1>
I am currently running the Localhost server via Visual Studio 2013. Please Help, Thanks!
You would need to include ngRoute inorder to use angular routing. So include ngRoute in your module as a dependency.
var TodoApp = angular.module("TodoApp", ["ngResource", "ngRoute"]).
config(.....
Also remember to include angular-route.js unless you are using very old version of angular that comes with routing as well. You can refer to the cdn http://code.angularjs.org/x.y.z/angular-route.js or download the file.
Plnkr

Resources