AngularJs UI-Router

ui-router :
uiRouter is an alternative router for AngularJS v1.0. Instead of configuring a list of routes, you configure states.
Changing State
There are three ways to change the state and thus change the UI

click a link with a ui-sref attribute
<a ui-sref="state-name">link text</a>
call

$state.go('state-name');

must inject $state to use

navigate to the URL of a state

typically by calling

$location.path(url)

or typing it into the browser address bar

state :

To define a route, we use the .config method and set our states on the $stateProvider.

var starter = angular.module('starter', ['ionic', 'controllerModule'])
.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('addOrder', {
      url: '/AddNewOrder',
      template: "<h1>HELLO!</h1>"
    }
    });
});
<body ng-app="starter">
    <div id='content' ng-controller='mainController'> 
         <a ui-sref="addOrder"> Add New Order </a></li>
         <div ui-view="main"></div>      
  </div>
</body>

template, templateUrl, templateProvider :

We can set up templates on each of our views using one of the three following options:

template – A string of HTML content or a function that returns HTML
templateUrl – A string URL path to a template or a function that returns a URL path string
templateProvider – A function that returns an HTML content string

$stateProvider.state('home', {
  template: '<h1>Hello {{ name }}</h1>'
});

URL :

The url option will assign a URL that the application is at to a specific state inside our app.

$stateProvider
  .state('inbox', {
    url: '/inbox',
    template: "<h1>Welcome to your inbox</h1>"
  });

When the user navigates to /inbox, then the app will transition into the inbox state and fill the main ui-view directive with the contents of the template “Welcome to your inbox”.

Views :

We can set multiple named views inside of a state. This feature is a particularly powerful one in ui-router: Inside of a single view, we can define multiple views that we can reference inside of a single template.

If we set the views parameter, then the state’s templateUrl, template, and templateProvider will be ignored. If we want to include a parent template in our routes, we’ll need to create an abstract template the contains a template.
Let’s say we have a view that looks like:

<div>
  <div ui-view="filters"></div>
  <div ui-view="mailbox"></div>
  <div ui-view="priority"></div>
</div>

We can now create named views that fill each of these individual templates. Each of the subviews can contain their own templates, controllers, and resolve data.

$stateProvider
  .state('inbox', {
    views: {
      'filters': {
        template: '<h4>Filter inbox</h4>',
        controller: function($scope) {}
      },
      'mailbox': {
        templateUrl: 'partials/mailbox.html'
      },
      'priority': {
        template: '<h4>Priority inbox</h4>',
        resolve: {
          facebook: function() {
            return FB.messages();
          }
        }
      }
    }
  });

Controller :

Just like in ngRoute, we can either associate an already registered controller with a URL (via a string) or we can create a controller function that operates as the controller for the state.

If there is no template defined (in one of the previous options), then the controller will not be created.

Steps to use the ui-router :

Download :

download from https://github.com/angular-ui/ui-router
just need one file from release folder… angular-ui-router.min.js

Include :

<script src="js/angular-ui-router.min.js"></script>

Add module dependency :

Add ui-router as a module dependency

var app = angular.module('app-name', ['ui.router']);

How to use :

  • use ui-view directive
  • When dealing with routes and states inside of ui-router, we’re mainly concerned with which state the application is in as well as at which route the web app currently stands.
    The templates we define at any given state will be placed inside of the

    <div ui-view></div>

    element of the route or state it was called. Each of these templates can include their own ui-view as well, which is how we can have nested views inside our routes.

    Wherever a view is desired use

    <div ui-view>initial content</div>

    When dealing with routes and states inside of ui-router, we’re mainly concerned with which state the application is in as well as at which route the web app currently stands.the templates we define at any given state will be placed inside of the

    <div ui-view></div>

    element.

    The ui-view directive tells $state where to place your templates. A view can be unnamed or named.

    <!-- Unnamed -->
    <div ui-view></div> 
    
    <!-- Named -->
    <div ui-view="viewName"></div>
    

    You can only have one unnamed view within any template (or root html). If you are only using a single view and it is unnamed then you can populate it like so:

    <div ui-view></div>
    
    $stateProvider.state("home", {
        template: "<h1>HELLO!</h1>"
    })
    

    The above is equivalent to specifying your view explicity, by name, in this case an empty name:

    $stateProvider.state("home", {
        views: {
            "": {
                template: "<h1>HELLO!</h1>"
            }
        }    
    })
    

    But typically you’ll only use the views property if you name your view or have more than one view in the same template. There’s not really a compelling reason to name a view if its the only one, but you could if you wanted, like so:

    <div ui-view="main"></div>
    
    $stateProvider.state("home", {
        views: {
            "main": {
                template: "<h1>HELLO!</h1>"
            }
        }    
    })
    

    Really though, you’ll use views to set up multiple views:

    <div ui-view></div>
    <div ui-view="chart"></div> 
    <div ui-view="data"></div> 
    
    $stateProvider.state("home", {
        views: {
            "": {
                template: "<h1>HELLO!</h1>"
            },
            "chart": {
                template: "<chart_thing/>"
            },
            "data": {
                template: "<data_thing/>"
            }
        }    
    })
    
  • use ui-sref directive
  • A directive that binds a link (“anchor(a)”) to a state. If the state has an associated URL, the directive will automatically generate & update the href attribute via the $state.href() method. Clicking the link will trigger a state transition with optional parameters. Also middle-clicking, right-clicking, and ctrl-clicking on the link will be handled natively by the browser.

    Usage:

    ui-sref=’stateName’ – Navigate to state, no params. ‘stateName’ can be any valid absolute or relative state, following the same syntax rules as $state.go()
    ui-sref=’stateName({param: value, param: value})’ – Navigate to state, with params.

    <!-- index.html -->
    <body>
        <div ui-view></div>
        <!-- We'll also add some navigation: -->
        <a ui-sref="state1">State 1</a>
    </body>
    

    Working Example :

    index.html
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
        <link href="css/style.css" rel="stylesheet">
        <script src="lib/angular.min.js"></script>
        <script src="lib/angular-ui-router.js"></script>
        <!-- your app's js -->
        <script src="js/app.js"></script>
        <script src="js/controllers.js"></script>
      </head>
      <body ng-app="starter">
        <div id='content' ng-controller='mainController'>
                    <a ui-sref="addOrder"> Add New Order </a>
                    <div ui-view="addOrderView"></div> 
                    <button ng-click='showOrders()'>Show Orders</button>               
                    <div ui-view="showOrdersView"></div>                  
        </div>
      </body>
    </html>
    
    app.js
    var starter = angular.module('starter', ['ui.router','controllerModule'])
    .config(function($stateProvider, $urlRouterProvider) {
      $stateProvider
        .state('addOrder', {
          url: '/AddOrder',
          views: {
          'addOrderView': {
            template: '<h4>Add Order</h4>'
          }
        }
        })
         .state('showOrders', {
          url: '/ShowOrders',
          views: {
          'showOrdersView': {
            template: '<h4>Show Orders</h4>'
          }
        }
        });
    });
    
    controllers.js
    angular.module('controllerModule', [])
    
    .controller('mainController', function($rootScope, $state, $stateParams) {
    	$rootScope.showOrders = function(){
    		$state.go('showOrders');
    	 }
    });
    

    For more info :

    https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stateproviderstatestatename-stateconfig

    http://www.ng-newsletter.com/posts/angular-ui-router.html

    http://java.ociweb.com/mark/other-presentations/AngularJS-ui-router.pdf

    http://cnpmjs.org/package/angular-ui-router

    https://github.com/angular-ui/ui-router/wiki/Quick-Reference#note-about-using-state-within-a-template

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s