Routing with angular js - javascript

My server using angular for routing. My server sending to the browser a HTML file that contains js file with routing (using angular js).
my server code (send to browser check.html contains the routing file main.js) :
var express = require("express");
var app = express(); // express.createServer();
app.use(express.static(__dirname + '/public'));
app.get("/*", function(request, response) {
response.sendFile(__dirname + '/public/check.html');
});
app.listen(8080);
check.html code:
<html data-ng-app="myApp">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
after the browser gets the check.html file he doesnt redirect it to main.js in order to use the routing. I tried to debug it but the browser is stuck without doing nothing. my app is local and the url im trying to connect to is:
http://localhost:8080/stations
and all the files are loaded correctly without any errors on the console.
main.js code:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/',
{
controller: 'HomeController',
templateUrl: 'menu.html'
})
.when('/stations',
{
controller: 'StationsController',
templateUrl: 'check2.html'
})
.when('/',
{
controller: 'HomeController',
templateUrl: 'menu.html'
})
.otherwise({redirectTo: '/'});
});
myApp.controller('StationsController', function($scope){
$scope.check = {name:"ELAD!!"};
});
check2.html code:
<html>
<head>
</head>
<body>
<div>
<p>{{check.name}}</p>
</div>
</body>
</html>

Ok let's start fresh on angular..
Angular 101
You may know angular is essential for Single Page Application so what happens is you supply the first page that is check.html in your case but you should name it index.html it's a convention. khair.. what happens is when a route transition occurs in the your angular code that is something after # an it's purely client end or a soft redirection. so angular fires an AJAX request to retrieve the resource matching your templateUrl from router. then plugs it inside the <div ng-view></div> thus the redirection. notice the ng-view.
Well bellow is the proposed solution
the link should be http://localhost:8080/#stations as the angular matches handles the routes after #. Other routes like the link you provided are handed to the server.
your check.html should look like this.
<html data-ng-app="myApp">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
and your check2.html should be in your public directory and have the code like
<div>
<p>{{check.name}}</p>
</div>

Related

AngularJS: routing not working using ng click

For my app, i have a login page that serves as index.html. Based on the user login, the app routes to different landing pages.
However, within one of the landing pages, I am routing to another page by using ng click and it does not fire. What am I doing wrong?
Is it possible that I can't route to another page from a landing page if the app is being served by index.html since the paths are absolute URLs?
In summary: I have 3 pages in my app: index.html (login page) and page1.html and page2.html. When the user logs into the app, he lands on page1.html. From here if he clicks a button then he should be sent to page2.html.
A working plunker would be highly appreciated.
Here is what I have in user1.html
User1.html
<html data-ng-app="myApp">
<head>
-----
</head>
<header>
-------
</header>
<body ng-controller="TestController">
<button ng-click="go('/user1')">Link</button>
------------------------------------------------------
<script type="text/javascript" src="../../webjars/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="../../webjars/angularjs/1.3.8/angular.min.js"></script>
<script src="//code.angularjs.org/1.2.20/angular.js"></script>
<script src="//code.angularjs.org/1.2.20/angular-route.js"></script>
<script src="//code.angularjs.org/1.2.13/angular-cookies.js"></script>
<script src="../js/app.js"></script>
</body>
</html>
Here is app.js
(function () {
'use strict';
var app = angular.module('myApp', ['ngRoute', 'ngCookies'])
app.config([
"$routeProvider","$locationProvider" ,
function($routeProvider,$locationProvider){
$routeProvider.when('/user1',{
templateUrl:"../html/page2.html",
controller: 'TestController'
});
$locationProvider.html5Mode(true);
}
]);
app.controller('TestController', ['$scope', '$location',function($scope, $location){
$scope.go = function (hash) {
$location.path(hash);
};
}
]);
})();
Plunker: https://plnkr.co/edit/8VdQIZDHcX36WhuKbAev

Angular+Node app ignores routing and doesn't load View into ng-view

I am developing a Node+Angular application. I am familiar with Angular, but a beginner in Node so I figured it would be a great start. I am not sure if the problem is with Node or with Angular, so I will just post the code here.
My folder hierarchy is:
- public
- AppAngular
- controllers
chatController.js
- models
- views
chatView.html
app.js
index.html
server.js
In my server.js, I've specified the code below:
app.get('*', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
I don't have any API, since the plan is to build a real-time chat with Socket.io, something I've always wanted to try out.
Anyway, my app.js looks like this:
var app = angular.module('ChatApp', ["ngResource"])
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'views/chatView.html',
controller: 'chatController'
})
.otherwise({
redirectTo: '/'
})
}])
I have referenced everything in my index.html like this:
<!DOCTYPE html>
<html ng-app="ChatApp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Chat</title>
<script src="/node_modules/angular/angular.js"></script>
<script src="/node_modules/angular/angular-resource.js"></script>
<script src="/public/AppAngular/controllers/chatController.js"></script>
<script src="/public/AppAngular/app.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<div ng-view></div>
</body>
</html>
There is no need to post contents of chatView.html and chatController.js since both are straightforward.
Does anyone have the slightest idea to what's the problem? I have a pretty similar config in one of my other projects, with dozens of routes and it works flawlessly but this.

ngRoute return 404 Not Found error

I'm building a simple personal contacts management app using AngularJS. I put all my files inside htdocs/angular-contacts/ folder of my Mac machine.
index.html
<!DOCTYPE html>
<html ng-app='ContactsApp'>
<head>
<title>Contacts</title>
<base href='/'></base>
</head>
<body>
<h1>Contacts</h1>
<div ng-view=""></div>
<script src='/angular-contacts/jquery-2.1.3.min.js'></script>
<script src='/angular-contacts/angular.min.js'></script>
<script src='/angular-contacts/angular-route.min.js'></script>
<script src='/angular-contacts/angular-route.min.js.map'></script>
<script src='/angular-contacts/app.js'></script>
<script src='/angular-contacts/controller.js'></script>
</body>
</html>
app.js
angular.module('ContactsApp', ['ngRoute']);
.config(function($routeProvider,$locationProvider){
$routeProvider
.when('/contacts',{
controller: 'ListController',
templateUrl: 'list.html'
});
$locationProvider.html5Mode(true);
});
controller.js
angular.module('ContactsApp')
.controller('ListController',function($scope){
$scope.contacts = [];
})
list.html
<p>List views...</p>
Why I go to http://localhost:8888/angular-contacts/contacts, I got 404 Not Found error.
How to fix this problem? How to load that list.html?
Note:
I'm using MAMP (Apache).
AngularJS: v1.3.14
Angular Route: v1.3.14
That's because
$routeProvider
.when('/contacts',{
controller: 'ListController',
templateUrl: 'list.html'
});
expects the http://localhost:8888/contacts location, not the http://localhost:8000/angular-contacts/contats location.
You should add the prefix in your route declaration, or even better, conifgure the virtual host, so you'll be able to use a real domain, rather than the localhost's sub-catalogue.

Angular routeProvider not loading next template

I am trying to have each item in a list have a button that uses $routeProvider to route to a template. However, I keep getting 404s when I hit the link (it goes to the right address, but no page loads). Any help on getting this code to work would be most appreciated:
angular.module('tipOutput', ['firebase', 'filters'])
.controller('Tips', ['$scope', 'angularFire',
function ($scope, angularFire) {
var ref = new Firebase('https://sitename.firebaseio.com/tips');
angularFire(ref, $scope, "tips");
}])
//routing to secondary pages
.config(['$routeProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/tips/:tipId', {template: 'partials/tip-detail.html', controller: 'Tips'}).
otherwise({redirectTo: '/'});
}])
And, in case it helps, here's the code of my template:
<html ng-app="TipOutput">
<body>
<div ng-view></div>
<script type="text/javascript" src="http://static.firebase.com/v0/firebase.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular-resource.min.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.3.0/angularfire.min.js"></script>
<script type='text/javascript' src='https://cdn.firebase.com/v0/firebase-simple-login.js'></script>
<script src="js/app.js"></script>
</body>
</html>
Routes in a single page app are really virtual routes. How does the webserver software know what to do with that url? What are you doing to map this url to the html file that is serving your app? I suspect you might need to setup your httpd so that it understands what is going on.

Angular JS: How to load js files in partials

Very new to AngularJS, I am guessing the term for what I am trying to do is lazy load. I have looked at several different blogs and I have not found a complete working solution that is purely using AngularJS.
I understand that if I put the <script src="js/process1.js"></script> in index.html, all works fine, I am trying to cut down on the amount of js that is pulled down on the initial load.
With the script tag sitting in the partial, it is never loaded so the P1Ctrl is never created. So currently, if a user go into the application and never goes to process55, the user still has the code there for process55 even though it was never used.
Is there a way to load the file and inject the objects created in the process1.js into the app defined in main, at the time process1 route is executed?
index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Large Angular App</title>
<link rel="stylesheet" href="lib/foundation/css/foundation.min.css" />
</head>
<body ng-app="largeApp" ng-controller="LargeAppController">
<div>
Home | Process1
</div>
<br/>
<br/>
<br/>
<ng-view>Test</ng-view>
<script type="text/javascript" src="lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular/angular-route.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
js/main.js:
var app = angular.module("largeApp", ['ngRoute']);
var appCtrl = app.controller("LargeAppController", function(){});
app.config(function ($routeProvider, $controllerProvider) {
// save references to the providers
app.registerCtrl = $controllerProvider.register,
$routeProvider.when('/', {templateUrl: 'partials/home.html'});
//Thinking I need to set up a resolve to fire off a script loader to load js.
$routeProvider.when('/process1', {templateUrl: 'partials/process1/process1.html'});
$routeProvider.otherwise({redirectTo: '/'});
});
partials/home.html:
<div>
Home Page
</div>
partials/process1.html:
<script type="text/javascript" src="js/process1/Process1Controller.js"></script>
Process 1 {{process1data}}
js/process1.js:
console.log("I made it here");
app.registerCtrl('Process1Controller',function($scope){
$scope.process1data = "Hello!";
}
]);
To implement lazy loading of controllers in simple way, you have to do the following:
Save $controllerProvider.register (which is the only method to add a controller into already bootstrapped AngularJS app) to variable in your app (main.js):
var app = angular.module('app',["ngRoute"]);
app.config(['$routeProvider', '$controllerProvider',
function($routeProvider, $controllerProvider) {
// remember mentioned function for later use
app.registerCtrl = $controllerProvider.register;
//your routes
$routeProvider.when('/', {templateUrl: 'partials/home.html'});
$routeProvider.when('/process1', {templateUrl: 'partials/process1.html'});
$routeProvider.otherwise({redirectTo: '/'});
}
]);
process1.html:
<script src="js/process1.js"></script>
<div ng-controller="P1Ctrl">
{{content}}
</div>
And now, in process1.js you use our registerCtrl:
app.registerCtrl('P1Ctrl', function($scope)
{
$scope.content = '...';
});
index.html probably remains the same. Check if your process1.js is being loaded (simply using console.log() right in the body of process1.js, not in P1Ctrl controller). If it isn't, include jQuery before Angular:
<script src="lib/jquery/jquery.js"></script>
<script src="lib/angular/angular.js"></script>
IMPORTANT: This method doesn't work with angular 1.2.0-rc.2 and 1.2.0-rc.3, because this little trick with jQuery doesn't work.
For more complex (and prettier) solution, with .js files as dependencies in route definitions, check that article: http://ify.io/lazy-loading-in-angularjs/ - it also works with rc.2 and rc.3. Here is plunk implementing described method: http://plnkr.co/edit/ukWikO5TVDtQ1l9WlrGD

Categories