3

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
});

3 Answers 3

1

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); 
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can output the variable using expression language as a data attribute, like this:

<div data-my-variable="${myVariable}" id="myDiv"></div>

And if you are using Jquery, you can use the attr function:

var output = $("#myDiv").attr("data-my-variable");

Comments

0

Try (I've never tried this - just and idea... please post if it is working):

<script>
angular.module('jspVariablesService', [])
.value("valueName",${yourVariable});
</script>

in <head></head> or at the beginning of body and then import jspVariableService in

var app = angular.module('myApp', ["jspVariableService"]); 

and use it in controller:

app.controller('myCtrl', ["$scope", "valueName" function($scope,valueName) {
  //use your value!
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.