Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JSP variable from javascript [Angular JS]

I am working with angular JS and JSP. i need to retrieve the session attribute variable from the JSP to my controller. My code is below

JSP

<html lang="en" ng-app="myApp">
<body>
    <div data-ng-controller="myCtrl as vm" style="height:100%">
        <md-content layout="row" style="height:100%">
            <div class="widget">
                <h2>Header</h2>
                <div ui-view></div>
            </div>
        </md-content>
    </div>
    <script type="text/javascript" src="/root/script/script.js"></script>
  <%
  String policy = session.getAttribute("POLICY_CHANGE");
  %> 
 </body>
</html>

JS

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   // i want to get the JSP variable here
});
like image 865
Shareer Avatar asked Sep 10 '26 01:09

Shareer


1 Answers

Set session value to hidden input.

<div data-ng-controller="myCtrl as vm">
     <input type="hidden" id="sessionData" />
</div>
<script>
     var data = '<%=request.getSession().getAttribute("POLICY_CHANGE")%>';
     document.getElementById("sessionData").value = data;
</script>

and get value

app.controller('myCtrl', function($scope, $document) {
   $scope.data = $document[0].getElementById("sessionData").value;
   console.log($scope.data); 
});
like image 143
Gurkan Yesilyurt Avatar answered Sep 11 '26 14:09

Gurkan Yesilyurt