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!!
Related
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;
})
});
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.
I am new in angular, want to do the next web site in angular
This would be the main structure:
The snippet1 is always fixed
The snippet3 is the dynamic part
If i click in the link1 or link2 of the snippet2,load would be in the snippet3 ().
Now I expose my doubt:
If i click in icons the snippet1, the load web page would be in snippet4.
Like the image:
Error, when i try install "express cors":
How could do it?
Prerequisites:
Node.js
Step #1: Setup a new project directory
app.js
css (folder)
main.css
snip3.css
snip4.css
ctrl (folder)
snip3Ctrl.js
snip4Ctrl.js
index.html
nodeServer.js
partials (folder)
snip3.html
snip4.html
Step #2: Install npm packages
From your project directory, run:
npm install express cors
Step #3: Copy and paste code
app.js
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/snip3.html',
controller: 'snip3Ctrl'
})
.when('/snip3', {
templateUrl: 'partials/snip3.html',
controller: 'snip3Ctrl'
})
.when('/snip4', {
templateUrl: 'partials/snip4.html',
controller: 'snip4Ctrl'
})
.otherwise({ template: '<h1>Not Found</h1>' });
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular Routing Demo</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css">
<script src="http://code.angularjs.org/1.5.0/angular.js"></script>
<script src="http://code.angularjs.org/1.5.0/angular-route.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="css/main.css" />
<script src="ctrl/snip3Ctrl.js"></script>
<link rel="stylesheet" href="css/snip3.css" />
<script src="ctrl/snip4Ctrl.js"></script>
<link rel="stylesheet" href="css/snip4.css" />
</head>
<body>
<div class="container" style="height: 100%;">
<nav id="navbar" class="navbar navbar-responsive">
<!-- snippet #1 here -->
</nav>
<div style="height: 200px;"></div>
<ng-view></ng-view>
</div>
</body>
</html>
nodeServer.js
var express = require('express'), cors = require('cors'), app = express();
app.use(cors());
app.use("/", express.static(__dirname));
app.listen(8080, function(){
console.log('CORS-enabled web server listening on port', 8080);
});
snip3Ctrl.js
angular.module('app').controller('snip3Ctrl', function($scope, $http) {
});
snip4Ctrl.js
angular.module('app').controller('snip4Ctrl', function($scope, $http) {
});
Step #4: Run the node server
From your project directory, run:
node nodeServer.js
Done!
It will serve your page to localhost:8080 by default. In case I forgot anything, post a comment and I will try to update the answer.
Try using ui-router for the routes.
In the main index.html, add the header navbar, and let the links manipulate the state of the application.
<body ng-controller="AppController">
<header>
<a ui-sref="Snippet4"></a>
</header>
<div ui-view></div>
</body>
That's the starting point for the html.
I'm using eclipse with angularJS for make the front-end of my app. Not first time I'm using angular but first time I'm using it with eclipse.
AngularJS plugin have been installed and I made the link between view and controllers. I convert my project to AngularJS project. Angular is working (an input ng-model="a" {{a}} does the job) but the chrome terminal give me an error :
Error: [ng:areq] http://errors.angularjs.org/1.5.0/ng/areq?p0=HomeController&p1=not%20aNaNunction%2C%20got%20undefined
index.html
<!DOCTYPE html >
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Mon Titre</title>
<link rel="stylesheet" type="text/css" href="resources/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="resources/css/style.css" />
<script type="text/javascript" src="https://code.angularjs.org/1.5.0/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.5.0/angular-route.js"></script>
<script type="text/javascript" src="resources/js/angular/controller/MainController.js"></script>
<script type="text/javascript" src="resources/js/angular/controller/HomeController.js"></script>
<script type="text/javascript" src="resources/js/angular/controller/CategoryController.js"></script>
<script type="text/javascript" src="resources/js/angular/app.js"></script>
</head>
<body >
<div ng-view></div>
</body>
</html>
app.js
var app = angular.module("app", ["ngRoute"]); // Already tried to inject controllers
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/accueil.html',
controller: 'HomeController'
})
.when('/categories', {
templateUrl: 'pages/categorie-list.html',
controller: 'CategoryController'
})
.otherwise({
redirectTo: '/'
});
});
HomeController.js
var app = angular.module("app",[]);
app.controller("HomeController", function($scope){
$scope.bonjour ='I\'m home controller !';
});
CategoryController.js
var app = angular.module("app",[]);
app.controller("CategoryController", function($scope){
$scope.bonjour = 'I\'m category controller';
});
Both .html contains just one {{bonjour}}.
Thanks for your help and sorry for this low english !
In HomeController.js and CategoryController.js replace
var app = angular.module("app",[]); // create new app module
with
var app = angular.module("app"); // use existing app module
After that move app.js script before controller scripts:
<script src="https://code.angularjs.org/1.5.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0/angular-route.js"></script>
<script src="resources/js/angular/app.js"></script>
<script src="resources/js/angular/controller/MainController.js"></script>
<script src="resources/js/angular/controller/HomeController.js"></script>
<script src="resources/js/angular/controller/CategoryController.js"></script>
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