Accessing JSP variable from javascript [Angular JS]

痴心易碎 提交于 2019-12-11 01:34:02

问题


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

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/42300219/accessing-jsp-variable-from-javascript-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!