Saturday, May 6, 2017

How to create AngularJS portlet in Liferay

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

Hello World in Liferay Angular Portlet
1. create liferay plugin with liferay mvc portlet tempalte
File > New > Other > Liferay > Liferay Plugin Project > Next
    Fill in "Project name" > Finish.


2. import angular.js
In view.jsp, add the following line to import angular.js

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



3. add ng-app into view.jsp
in view.jsp, add the following tag

<section ng-app="helloAngularJS">

</section>



4. create angularJS controller
in view.jsp, create controller inside the ng-app

<div ng-controller="helloController" >

</div>



5. in main.js, create the ng app and controller

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

myApp.controller('helloController', ['$scope', function($scope) {

    // some controller code

}]);



AngularJS Portlet setup is done.
below are some sample codes how angularJS works

6. add the following html code inside helloController in view.jsp

<form>

<label>Name:</label>

<input type="text" name="username" ng-model="username">

<button ng-click="reset()">Reset</button>

<p>Your username is {{username}}</p>

</form>



7. add the following javascript inside helloController in main.js

$scope.username = 'unknown';

$scope.reset = function() {

    $scope.username = '';

};



8. Full source code for view.jsp

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ page import="com.liferay.portal.kernel.util.StringUtil" %>

<portlet:defineObjects />

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

<section ng-app="StudentPlayApp">

    <div ng-controller="UserController" style="border: solid black 1px">

        <h2>AngularJS Controller Example</h2>

        <form>

        <label>Name:</label>

        <input type="text" name="username" ng-model="username">

        <button ng-click="reset()">Reset</button>

        <p>Your username is {{username}}</p>

        </form>

    </div>    

</section>



9. Full source code for main.js

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

myApp.controller('UserController', ['$scope', function($scope) {

    $scope.username = 'unknown';

    $scope.reset = function() {

        $scope.username = '';

    };

}]);




Done !!

LinkWithin

Related Posts Plugin for WordPress, Blogger...