AngularJS, $routeProvider - javascript

I'm trying to learn how routes work in AngularJS to make a little application that allows users to login and write comments in a live feed. However the whole concept of routes is a bit blurry for me atm and i can't get this right.
My standard index.html containing an ng-view and necessary scripts.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="//cdn.firebase.com/js/client/1.0.21/firebase.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/0.8.2/angularfire.js"></script>
<script src="//cdn.firebase.com/js/simple-login/1.6.3/firebase-simple-login.js"></script>
<script src="controller.js"></script>
<title>Test Login App</title>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
My controller containing module and routeprovider.
var myApp = angular.module('myApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase',
'firebase.utils',
'simpleLogin'
]);
myApp.config(function($routeProvider) {
$routeProvider.
when('/', { controller: handleCtrl, templateUrl: 'handler.html' }).
when('/chatt', { controller: MyController, templateUrl: 'chat.html' }).
when('/login', { controller: loginCtrl, templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
}])
myApp.controller('MyController', ['$scope', '$firebase',
function($scope, $firebase) {
//CREATE A FIREBASE REFERENCE
var ref = new Firebase("https://ivproj.firebaseio.com/");
// GET MESSAGES AS AN ARRAY
$scope.messages = $firebase(ref).$asArray();
//ADD MESSAGE METHOD
$scope.addMessage = function(e) {
//LISTEN FOR RETURN KEY
if (e.keyCode === 13 && $scope.msg) {
//ALLOW CUSTOM OR ANONYMOUS USER NAMES
var name = $scope.name || 'anonymous';
//ADD TO FIREBASE
$scope.messages.$add({
from: name,
body: $scope.msg
});
//RESET MESSAGE
$scope.msg = "";
}
}
}
]);
The $routeprovider function should direct me to handler that is a simple .html file containing two buttons that in turn redirects to other htmls.

I think you have the syntax of the otherwise call in your config section wrong. Change what you have for this instead:
otherwise('/handler');
hope this helps...

you are missing '' in controller part. correct code should look like -
myApp.config(function($routeProvider) {
$routeProvider.
when('/', { controller: 'handleCtrl', templateUrl: 'handler.html' }).
when('/chatt', { controller: 'MyController', templateUrl: 'chat.html' }).
when('/login', { controller: 'loginCtrl', templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});
Make sure that you are referring the correct path in templateUrl.
and look at my earlier post to get a better idea - How to navigate in Angular App

myApp.config(function($routeProvider) {
$routeProvider.
when('/', { controller: 'handleCtrl', templateUrl: 'handler.html' }).
when('/chat', { controller: 'MyController', templateUrl: 'chat.html' }).
when('/login', { controller: 'loginCtrl', templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});
The $routeProvider.when() method in the above code actually creates a route with the given configuration. And the three .when()'s are creating three different routes.
But in your $routeProvider.otherwise('/handler'), you are telling angular to go to a route called /handler if the user tries to navigate anywhere outside the configured routes.
The mistake you are doing here is, you did not define a route at /handler. So you need to first define that route and then use it in .otherwise().
Try changing your configuration to reflect the below.
myApp.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/handler', { controller: 'handleCtrl', templateUrl: 'handler.html' }).
when('/chat', { controller: 'MyController', templateUrl: 'chat.html' }).
when('/login', { controller: 'loginCtrl', templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});

Related

Angularjs route doesn't works without # in URL

I have a problem with my angularjs routes. My simplified route config looks like:
App.config([ '$routeProvider', function( $routeProvider ) {
$routeProvider.
when('/', {
redirectTo: '/home'
}).
when('/home', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
}).
when('/404', {
templateUrl: '404.html'
}).
when('/500', {
templateUrl: '500.html'
}).
when('/:tabName', {
templateUrl: 'tabView.html',
controller: 'TabContentCtrl'
}).
when('/:tabName/:widgetName', {
templateUrl: 'tabView.html',
controller: 'TabContentCtrl'
}).
otherwise({
redirectTo: '/404'
});
}]);
The problem is when I put URLs http://myapp or http://myapp/ into browser, it redirects me nowhere, nothing takes place, even redirect to 404 error page. It starts working when I put hash to URL http://myapp/#, then it works as I expected. But why my default route for root URL of application http://myapp, and http://myapp/ did not work?
You just need to enable html5mode:
config javascript
App.config([ '$routeProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
}]);
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="/">
</head>
</html>
It depends on how have you set your virtual host and is it pointing to your root index.html? If yes, then if you type http://myapp it would definitely take you to http://myapp/#/home

which is best to `mainApp.config(['$routeProvider', function($routeProvider)` and `mainApp.config(function($routeProvider)`

I have just started learning angularJS but i can notice the same thing so many time that at some places when we start writing a function in angularJS i noticed that some people define the function they are going to use like this
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
}]);
But the same function is working fine if we just write the function without this ['$routeProvider' like this
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
});
I know there is no big difference when coming to code writing but still is there any difference in both the ways. If yes, then is it about minifying? and is there any negative point other that that of using it?
Thanks in advance!
mainApp.config(['$routeProvider', function($routeProvider) {
}]);
This type define a controller is callled Inline Array Annotation. And It is min-safe. min-safe mean if you minify your code then it will still work.
mainApp.config(function($routeProvider) {
});
This type of define a controller is called 'Implicit Annotation'. And its not min-safe. min-safe mean if you minify your code then it will not work.
And there a another way to declare a controller $inject Property Annotation
var MyController = function($scope, greeter) {
// ...
}
MyController.$inject = ['$scope', 'greeter'];
someModule.controller('MyController', MyController);
read more info click here

$routeProvider / $locationProvider not a function in AngularJS Routing

I'm trying to create so-called 'SEO-friendly' URLs in AngularJS.
In my script.js for the routing I have:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.html5Mode(true);
when('/blog', {
templateUrl: 'blog.html',
controller: 'BlogController'
}).
when('/page/ideas', {
templateUrl: 'ideas.html',
controller: 'IdeasController'
}).
otherwise({
templateUrl: 'home.html'
});
}]);
app.controller("BlogController", function($scope) {
$scope.title = 'Blog';
});
app.controller("IdeasController", function($scope) {
$scope.title = 'Ideas';
});
To remove the # from the URL, I am enabling the html5 mode with:
$routeProvider.html5Mode(true);
however, this results in the following error:
Failed to instantiate module exampleApp due to:
TypeError: $routeProvider.html5Mode is not a function
Does anyone have a solution for this issue? It means that the content will not display from the views because of it.
Edit: for anyone wondering, the working code is:
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/blog', {
templateUrl: 'blog.html',
controller: 'BlogController'
}).
when('/page/ideas', {
templateUrl: 'ideas.html',
controller: 'IdeasController'
}).
otherwise({
templateUrl: 'home.html'
});
$locationProvider.html5Mode(true);
}]);
html5mode method is available there on $locationProvider provider.
You should include $locationProvider in your config phase to make that dependency available in config block & then enable html5mode for # free URL.
Code
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
//$routerProvider code here
$locationProvider.html5Mode(true);
}]);
Additionally you have to add <base href="/"> tag on the index.html page

Angular Set Controller and routeParams

I'm using routeProvider to set the controller and a route param when my application is configured. Here's the code that I'm using:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/person/:uuid/report', { controller: 'CandidateCtrl' }).
when('/person/:uuid/confirm', { controller: 'ConfirmCtrl', }).
when('/person/add', { controller: 'AddCtrl' })
}]);
However, the controller is not being set correctly. Additionally, when I set the controller with ng-controller in the page itself, the routeParams object is empty. What am I doing wrong?
Edit:
I've also tried this, which also isn't associating the controller with the page nor setting the route-params.
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/person/:uuid/report', { controller: 'CandidateCtrl', template: 'templates/report.html' }).
when('/person/:uuid/confirm', { controller: 'ConfirmCtrl', template: 'templates/confirm.html' }).
when('/person/add', { controller: 'AddCtrl', template: 'templates/add.html' })
}]);
Here's the controller that I'm testing this out with:
appController.controller('CandidateCtrl', ['$routeParams',
function($routeParams) {
console.log($routeParams);
}]);
Try to add templateUrl
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/person/:uuid/report', {
templateUrl: 'partials/CandidateCtrl.html', //TODO : replace with the good template
controller: 'CandidateCtrl'
}).
when('/person/:uuid/confirm', {
templateUrl: 'partials/ConfirmCtrl.html', //TODO : replace with the good template
controller: 'ConfirmCtrl'
}).
when('/person/add', {
templateUrl: 'partials/AddCtrl.html', //TODO : replace with the good template
controller: 'AddCtrl'
}).
otherwise({
redirectTo: 'Something' //TODO : replace with the good url
});
}]);
I was serving the views by via my web-mvc. I've since changed it to serve a layout and have the partial pages be kept in the resource folder.

$routeProvider is unknown

I have added the scripts like this
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="Scripts/angular-resource.min.js"></script>
<script src="Scripts/test.js"></script>
and I did this in my test.js
var app = angular.module('MyApp', ['ngRoute']).config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login.html',
controller: 'loginController'
});
$routeProvider.otherwise({ redirectTo: '/login' });
});
app.controller('loginController', function () {
})
I got that the $routeProvider is unknown.
I have read many questions about this and I tried the solutions but nothing works.
help please
notethe angular library is working
I can make binding for example
Try
<div ng-app="MyApp" ng-controller="loginController">{{test}}</div>
then
var app = angular.module('MyApp', ['ngRoute']).config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login.html',
controller: 'loginController'
});
$routeProvider.otherwise({
redirectTo: '/login'
});
});
app.controller('loginController', function ($scope) {
$scope.test = "test me"
})
Since Angular 1.2 - ngRoute module is separated as component, you have to include angular-route.js, then you will have your providers.
https://github.com/angular/angular.js/commit/5599b55b04788c2e327d7551a4a699d75516dd21
https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes-12

Categories