Tuesday, May 16, 2017

How to use ui-router in AngularJS Portlet

Platform:
- Liferay 6.x, Liferay 7.0
- AngularJS 1.6.x

In this example, we will also continue from the first angularJS portlet created in earlier post.
the differences with the ngRoute example are main.jsp

Steps
1. create 2 new jsp for the ui-routing example in the same folder with view.jsp
- page1.jsp, with the following content

<h2>This is the page 1.</h2>


- page2.jsp, with the following content

<h2>This is the page 2.</h2> 


2.in view.jsp, import angular-ui-router.min.js.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js" />



3. in view.jsp, create _contextPath variable

<script>
     var _contextPath = '${pageContext.request.contextPath}';
 </script>


4. in view.jsp, add the controller and routing url

<div ng-app="RoutingApp">
     <h2>AngularJS Routing Example</h2>
     <p><a ui-sref="page1" >page 1</a> | <a ui-sref="page2">page 2</a></p>
     <div ng-view></div>
 </div>



5. in main.jsp, add the ui-router to angular module

var myApp = angular.module('RoutingApp', ['ui.router']);


6. in main.jsp, add the routing configuration

myApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', 
    function($stateProvider, $urlRouterProvider, $locationProvider) {
       var page1State = {
         name: 'page1',
         url: '/page1',
         templateUrl: _contextPath + '/page1.jsp'
       }

       var page2State = {
         name: 'page2',
         url: '/page2',
         templateUrl: _contextPath + '/page2.jsp'
       }


       $stateProvider.state(page1State);
       $stateProvider.state(page2State);
       $urlRouterProvider.otherwise('/');

 }]);



 Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...