If you want to avoid injecting username
and password
directly into index.html
for angularjs controller/services, there are better ways to handle authentication. It's recommended to either use an authorization token or set up a cookie that can be automatically sent by the browser if the user is already authenticated when the angular managed page loads (assuming both the jsp app and angular app are on the same domain).
When it comes to injecting data for angularjs usage, there are two approaches to consider. The second option is preferred as it does not clutter the global scope.
One method is to inject it as a global variable and access it using $window
. For example, have your server-side .jsp
render a script tag with a global variable like this:
<script type="type/javascript">
var pass = 'whatevervalue';
</script>
You can then access this variable in your controller using $window
:
angular.module('yourapp').controller('YourCtrl', $window){
console.log($window.pass);
}
- You can also utilize angular-preloaded to inject your variables in a
type="text/preloaded"
script tag and make them accessible to your controller through the $preloaded
service.
Your jsp can output data like this:
<script type="text/preloaded">
{
"data": "point"
}
</script>
In your controller, you can retrieve this data as follows:
angular.module('app', ['gs.preloaded'])
.controller('SomeCtrl', function ($preloaded) {
// do something with $preloaded.
$preloaded; // => { data: "point", another: { point: "of data" } }
});
Make sure to place your preloaded script before your controller script for it to work correctly. As mentioned in the documentation:
NOTE: Your script tags must run before anything using $preloaded, so I suggest putting them in your document's head.