Hi guys, I am gonna write a very basic and simple angular js routing application, purpose of writing this article is
just to provide quick start with angularjs routing
Here we go.
I am gonna create a simple application “mailApp”, I will create an angularjs module and will configure this with my html file.
First thing we need is to create a html file where we configure our angularjs application.
I create index.html with following code
index.html
<html>
<head>
<title>My angular routing</title>
<meta content="">
<style></style>
<script src="http://angular.min.js"></script>
<script src="http://angular-route.min.js"></script>
<script src="http://app.js"></script>
<script src="http://controllers.js"></script>
</head>
<body>
</body>
</html>
As you might noticed ng-app=”mailApp” this is how we bind our mailApp with index.html.
To get start using angularjs we need two js files either download from angularjs or use cdn
1. angular.min.js
2. angular-route.min.js
If you want to use cdn that is even more easy.
//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.12/angular.min.js
//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.12/angular-route.min.js
all setup with angularjs, lets create our application.
I have divided my application in two files
1. app.js: module and configuration
2. controllers.js: controllers
It is good idea to keep controllers separate to have code more manageable
lets start with app.js
Create new js file name it app.js
app.js
var mailApp = angular.module('mailApp',['ngRoute', 'mailControllers']);
mailApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/test', {
templateUrl: 'template.html',
controller: 'testController'
}).
otherwise({
redirectTo: '/home'
});
}]);
In above code I have created my mailApp and registered it with angularjs with dependency of ngRoute and mailControllers,
ngRoute is the angularjs routing api and mailControllers is controller package defined in our controllers.js
I have defined a route if url is #/test then it should call my testController (Defined in controllers.js) and attach template.html
as a view (you can place some html in tmeplate.html file)
Note: template.html file should be location in path relevant to url.
Lets write controllers.js to create mailControllers package.
controllers.js
var mailControllers = angular.module('mailControllers', []);
mailControllers.controller('testController', ['$scope', '$http',
function ($scope, $http) {
/*
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
*/
alert("Hurray... my controller is on");
//$scope.orderProp = 'age';
}]);
I have registered my controllers package “mailControllers” with angularjs
Now I create testController and register it with mailControllers.
That’s it. Now run your index.html file in browser and you will see the alert.
cheers!!!
1 Response
[…] Very simple and basic angularjs routing application […]