Creating the page navigation using states

After all the work done in the last two tutorials we are about to do the real stuff which we need to do. In our app on the right side we always see the description of the car and now we are going to include a button labeled “More” and on click of the “More” we are to navigate to a new page. Let’s do that one by one.

mainController.js

app.config(function($stateProvider,$urlRouterProvider,$locationProvider){     $locationProvider.html5Mode(true);     $urlRouterProvider.otherwise('/index.html');    $stateProvider         .state('home',{             url:'/index.html',             templateUrl: '/templates/home.html'         })    .state('more',{         url:'/more',         templateUrl:'templates/more.html'         }); });

In the above config block we have introduced our second state “more” and created the object with url as “/more” and its templateUrl as more.html.

Now we need to create more.html file under templates and for now the content of the file is just <div>More</div>

Now that we are set with our states we need to think about the state change trigger which is nothing but the More button and its handler in the controller. Lets quickly create a “More” button inside our home.html

home.html

<div  style="float:left;margin-right:10px"> 	<car-details ng-repeat="car in cars" src="{{car.url}}"  title="{{car.name}}" ng-click="onSelect($index)"></car-details> </div> <div>     {{desc}}     <button style="background-color:33C4FF" ng-click="onClickMore()">More</button> </div>

mainController.js

app.controller('mainController',function($scope,carService,$state){          $scope.cars = carService.requestCarDetails(function(cars){        $scope.cars = cars;        $scope.desc = $scope.cars[0].desc;     });          $scope.onSelect = function(index){        $scope.desc= $scope.cars[index].desc;     }          $scope.onClickMore = function(){         $state.go("more");     } });

In the above code its very simple we have handler and also the injected $state service which will help us to transition to a different state by providing the new state’s name as a parameter of the “go” method.

Creating the page navigation using states 1

On click of More will take us to a new page, technically its not a new page its always inside the same application.

Creating the page navigation using states 2

Now that we are able to transition from one state to other but we are just seeing the dummy “More” page as of now. In the next tutorial we will see how we can pass params in the state and display the selected contents in the More page.

Download Demo

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *