Before you start, all the code below is working on: http://jsbin.com/roqil/edit
To have control of redirecting pages you need to follow a few steps before.
Reference the Angularjs routing libraries
Reference the module ngRoute
in your html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-route.min.js"></script>
</head>
Modularize your App
It is only possible to control the routing of the page with a modularized application, create your module referencing the angular-route
thus:
var app = angular.module("app", ["ngRoute"]);
And on the tag <html>
add :
<html ng-app='app'>
The variable app
is global and in it you can call services
, factories
, and configuration methods.
Let’s add a factory
of tasks only to ensure that controllers
are using the same tasks list. So, the two controllers, one for the view of Detalhes
and another to Listagem
:
/*1*/ app.factory("TaskFactory",function(){
/*2*/ var tasklist = [
/*3*/ {name:"terminar meu app",id:0},
/*4*/ {name:"comprar presente para minha irmã",id:1}
/*5*/ ];
/*6*/ return{
/*7*/ get : function(){
/*8*/ return tasklist;
/*9*/ }
/*10*/ };
/*11*/ });
/*12*/ app.controller('TaskListCtrl', function ($scope,TaskFactory) {
/*13*/ (function(){$scope.tasks=TaskFactory.get();})();
/*14*/ });
/*15*/ app.controller('TaskDetailCtrl', function ($scope,TaskFactory,$routeParams) {
/*16*/ (function(){$scope.task=TaskFactory.get()[$routeParams.taskId];})();
/*17*/ });
Details of the Lines:
Line 1 - Creating the factory
Line 3 - We will use the id
of the task to call it view
listing for details
Line 6 - Returning a method to call the tasks list from factory
Line 12 - Creating the controller
TaksListCtrl
which is receiving by argument the $scope
and TaskFactory
which is Factory. It has to be the same name called in the argument and recorded in the app.factory()
Line 13 - Populando $scope.tasks
with the list of tasks that returns from TaskFactory.Get();
Line 15 - Creating the controller
TaskDetailCtrl
who will be responsible for presenting the task selected in the other view
. The difference is that now I’m getting by argument the $routeParams
module ngRoute
who is responsible for keeping the data you pass on URL
Line 16 - Again I’m picking up tasks from TaskFactory
but this time I’m filtering for those that contain the id = $routeParams.taskId
(we will see ahead why this) then it will bring only one task.
I could do that too if you prefer:
//esta forma
var tasks = TaskFactory.get();
var id = $routeParams.taskId;
$scope.task = tasks[id];
//é a maneira simplificada desta
$scope.task=TaskFactory.get()[$routeParams.taskId];
Configure the routes in app.config()
You need to reserve a space in html to allow Angularjs to manipulate your DOM
<body>
<div >
<ng-view></ng-view>
</div>
</body>
Just use the directive ng-view
at some tag <div>
You don’t need to reference controllers or anything like that, it will be recorded in app.config()
next:
/*1 */ app.config(function($routeProvider) {
/*2 */ $routeProvider.when('/',{
/*3 */ template: 'Lista de Tasks:'+
/*4 */ '<div >'+
/*5 */ '<div ng-repeat="task in tasks">'+
/*6 */ '{{task.id}} - {{task.name}}'+
/*7 */ '<div><a ng-href="#/{{task.id}}">detalhes</a>'+
/*8 */ '</div></div>'+
/*9 */ '</div>',
/*10*/ controller: "TaskListCtrl"
/*11*/ }).
/*12*/ when('/:taskId',{
/*13*/ template: 'Detalhes da Task {{task.id}}:'+
/*14*/ '<h4>Nome: {{task.name}}</h4>'+
/*15*/ '</div>'+'<a ng-href="#/"> Voltar</a>',
/*16*/ controller: "TaskDetailCtrl"
/*17*/ }
/*18*/ ).otherwise({redirect:'/'});
/*19*/ });
What the above code does is:
Line 1 - invoke method config
of the module passing a function
who receives the $routeProvader
Line 2 - No $routeProvader
you have the methods when()
and otherwise()
, each receives an object with the routing properties, for example:
when("/url que vc deseja",{
template: "aqui vai o html que será renderizado dentro de ng-view"
controller: "aqui o nome do controller correspondente àquela url"
});
otherwise({redirect:"/"}) //quer dizer que se nao for nenhuma das url registradas,
// redirecionara para a principal
In the first when()
I am passing that if you do not have parameters, you will call that template using "Tasklistctrl". If the template is too large, it is recommended to store it in another file and call it so {templateUrl:'exemplo.html'}
alas instead of just template
On line 7 I am simply creating a link to #/{{task.id}}
, the angular will replace the taskId
by the id of the task.
IMPORTANT: On line 12 o when
are receiving \:taskId
, the sign :
indicates that it is a parameter, this is necessary to say to the $routeParams
which is called in the controller
, that he will own the property taskId
, see:
In addition, is passing the template
and tying to the controller TaskDetailCtrl
Summary
Ready, these steps are necessary to make a simple routing control using Angularjs
summing up:
- Referencing angular.js and angular-route.js
- Create a module for the application referencing
['ngRoute']
- Add
<html ng-app='nomeDoModulo'>
- Create controllers and Factories/serivces
- Add argument
$routeParams
in the controller using this.
- Call ng-view in html like this:
<div ng-view></div>
- Invoke
app.config(function($routeProvider){...})
to register routes (including the $location
only works if the route is registered here.
- Call the method
$routeProvider.when()
for each route of your application passing the correct parameters
- Distribute tags
<a href="#/rotaEscolhida">
- Utilise
$routeParams.qualquerPropriedadeRegistrada
as needed.
App running here: http://jsbin.com/roqil/edit
Update
In this example I used the native router of angular, but there is another much better Ui-Router
Worth checking out this link:
How to use Angular UI Router? and what are the advantages?
wrote this code and this post all too fast! congratulations.
– Leandro RR
Thank you (: it actually took me a few hours to write it
– anisanwesley
now that I saw that the post was made 10 days ago, anyway, your response was great. makes a blog and passes your knowledge to us. ;-)
– Leandro RR
I have tried to set up a blog, it did not go very well kk. I will share my knowledge here, on demand of the questions [:
– anisanwesley