Can angular.js communicate with JSTL expression language?

3.6k views Asked by At

Can angular.js communicate with JSTL expression language? I want to create ng-options using an array. Something like this :

<select ng-model="detail" ng-init="Categories = '${Categories}'" ng-options="'${Category.code}' for Category in Categories">
 

2

There are 2 answers

0
David Ballester On BEST ANSWER

There can't be such thing as an angular-JSTL communication, but you can still achieve what you are looking for. JSPs will be evaluated server-side generating a final static HTML to be send to the client-side, where the Angular application does its magic. So, the JSTL is evaluated server-side, being impossible for the Angular application to "communicate" with it.

In your case, let's assume you have these variables assigned like this:

Categories = '[{"code": "foo", ...}, {"code": "bar", ...}]'

Now, your JSP contains this line:

<select ng-model="detail" ng-init="Categories = '${Categories}'" ng-options="'${Category.code}' for Category in Categories">

Once the JSP is evaluated, what Angular will find is this:

<select ng-model="detail" ng-init="Categories = '[{"code": "foo", ...}, {"code": "bar", ...}]'" ng-options="'' for Category in Categories">

This may be close to what you want to do, but I think the way to approach this is:

JSP:

window.categories = ${Categories};

That is assuming your categories variable is a JSON. If it isn't, you may have to convert it to JSON using Jackson, or manually through JSTL (which I would encourage you not to do). Now, you have a javascript variable containing whatever your categories are, so you can use regular Angular logic to iterate it.

Let's say you have a FooController that looks something like this:

angular.module("controllers")
    .controller("FooController", [
      "$scope",
      "$window",

      function($scope, $window) {
        $scope.categories = $window.categories;
      }
    ]);

Now you have your categories in the scope, so you can use them in your view like this:

<select ng-model="detail" ng-options="'category.code for category in categories">
0
monkai On

I believe the answer yes (I'd love to test this but I'm a bit tied up at the moment). JSTL is processed server-side to render HTML (amongst other things). AngularJS is something that is processed client-side.

So, it is my understanding that in you example above gave, the "categories" attribute would be set the string output of the ${Categories} JSTL EL evaluation.