AngularJS: routing not working using ng click - javascript

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

Related

Routing with angular js

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>

understanding routes and templates html in angularjs, simples example possible

I'm trying to embed angularjs into my existing asp.net mvc4 app.
(Views/Shared/)
_Layout.cshtml
<html data-ng-app="myApp">
<head>
<script src="~/Scripts/angular.min.js"></script>
<script src="/js/main.js"></script>
</head>
<body>
#RenderBody()
</body>
</html>
/js/main.js
var app = angular.module("myApp", []);
module.config(function ($routeProvider) {
$routeProvider.when("/topics", {
controller: "topicsController",
templateUrl: "/js/templates/topicsView.html"
});
$routeProvider.otherwise({ redirectTo: "/" });
});
app.controller("topicsController", function ($scope) {
$scope.testData = "some dummy data";
});
/js/templates/topicsView.html
<h1>topics template view, dummy object </h1>
{{ testData }}
and inside /Views/Home/Index.cshtml
<div data-ng-view=""></div>
I'm trying to navigate to /topics using #/topics url but nothing is rendered (blank page, not 404), not even h1 title from templates/topicsView.html
What I'm doing wrong?
You forgot to include ngRoute module. Try this:
var app = angular.module("myApp", ['ngRoute']);
You need to include angular-routes.js along with angular.js and then include ngRoutes modules as a dependency when you create the angular main app module.

How to initialize controllers manually after bootstrapping angular app using angular.bootstrap?

Found solution to this question.
I have a normal javascript app.I want to embed my angularjs app into it by bootstrapping manually.The problem is that "controllers with that module is not at all initialized"
index.html:
<html>
<head> <title>Including angular app into another</title> </head>
<body>
//I have normal javascript app
<div>First App</div>
<div id="secondApp">
<div class="container" ng-include="'views/main.html'" ng-controller="MainCtrl"> </div>
</div>
//included all libraries required for the app
<script src="jquery.js"></script>
<script src="angular.js"></script>
//main.js
<script src="scripts.js"></script>
</body>
</html>
scripts.js:
angular.module('sampleApp', []);
// in this way, i have bootstrapped the app
angular.bootstrap(document.getElementById('secondApp'), ['sampleApp']);
angular.module('sampleApp')
.controller('MainCtrl', function($scope, $rootScope, $timeout) {
//i have included the functionality required for my second app
});
But it is not embedding angular app into first app, getting an error "Argument 'MainCtrl' is not a function, got undefined"
I don't understand, where i am doing wrong.
Just bootstrap the whole app in index.html instead of doing this in scripts.js like this
<script type="text/javascript">
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('secondApp'), ['assetWidgetApp']);
});
</script>
Thanks!!!
The order of the statements is wrong. It should be:
angular.module('sampleApp', []);
angular.module('sampleApp')
.controller('MainCtrl', function($scope, $rootScope, $timeout) {
//i have included the functionality required for my second app
});
// in this way, i have bootstrapped the app
angular.bootstrap(document.getElementById('secondApp'), ['sampleApp']);
You need to define the controller before you bootstrap the angular app.

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