Thursday, May 11, 2017

How to use ngRoute in AngularJS Portlet

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

In this example, we will continue from the angularJS portlet created in earlier post.
1. create 2 new jsp for the routing example in the same folder with view.jsp
- first.jsp, with the following content.

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


- second.jsp, with the following content

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




2. in view.jsp, import angular-route.min.js

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-route.min.js">



3. in view.jsp, create the _contextPath variable

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



4. in view.jsp, add the page routing controller.

<div ng-app="RoutingApp">
    <h2>AngularJS Routing Example</h2>
    <p>Jump to the <a href="#/first">first</a> or <a href="#/second">second page</a></p>
    <div ng-view></div>
</div>



5. in main.jsp, add the ngRoute to angular module

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



6. in main.jsp, add the routing configuration

myApp.config( ['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/first', {
            templateUrl: _contextPath + '/first.jsp'
        })
        .when('/second', {
            templateUrl: _contextPath + '/second.jsp'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);


p/s: the _contextPath variable is important in Liferay environment to reach the pages inside portlet folder.


Done!!

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...