Angular JS Magazine

marți, 7 octombrie 2014

Angular JS - Routing Without a Controller

Angular allows us to use rooting without an explicit controller. Per example, below we have view1.html and view2.html. The first route, /views/view1.html, uses a controller, while the second route, /views/view2.html, uses only the templateUrl:


<div id="atpPanel" class="panel">
    <h3 class="panel-header">ATP SINGLES RANKINGS - VIEW 1</h3>
    <table class="table">
        <tr ng-repeat="item in atpPlayers">


<div id="atpPanel" class="panel">
    <span class="label label-primary">This is view 2</span>

Routing code:

<!DOCTYPE html>
<html data-ng-app="myApp">
    <script src="../angular/angular.min.js"></script>
    <script src="../angular/angular-route.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
        var app = angular.module("atpModule", ['ngRoute'])
                .config(function ($routeProvider) {
                            .when('/', {
                                templateUrl: './views/view1.html',
                                controller: 'atpCtrl1'
                            .when('/view2', {
                                templateUrl: './views/view2.html'
                            .otherwise({redirectTo: '/'});
                .controller("atpCtrl1", function ($scope) {
                    // Will be printed in 'view1'
                    $scope.atpPlayers = [
                        { name: 'Nadal, Rafael (ESP)', rank: 1 },
                        { name: 'Djokovic, Novak (SRB)', rank: 2 },
                        { name: 'Federer, Roger (SUI)', rank: 3 },
                        { name: 'Wawrinka, Stan (SUI)', rank: 4 },
                        { name: 'Ferrer, David (ESP)', rank: 5 }
<h2>Routes and Views</h2>
<a href="#/view1" title="Open 'view1'">Open 'view1'</a>
<a href="#/view2" title="Open 'view2'">Open 'view2'</a>

<!-- AngularJS views will be loaded here on page navigation -->
<div ng-app="atpModule" ng-view=""></div>