Reputation: 1284
Converting from Grails / GSP custom tag to AngularJS Directive
I have an existing Grails / GSP tag lib that will generate a link that will be displayed by a remote server, loading content from the local server. The URL in the link must be the full path. The custom GSP tag lets me specify the action right in the GSP. I need to replace this using AngularJS, and I understand that directives are the way to go. Is there an easy way to pass parameters from the tag in a GSP into the directive?
Are there equivalent functions to the "grailsLinkGenerator" that I can use to generate the URL inside the directive?
My existing Grails / GSP tag looks something like this:
GSP:
<g:myRemoteLink action="alpha" update="targetDiv" id="${ent.id}" >Show Alpha</g:myRemoteLink>
MyTagLib.groovy:
def myRemoteLink = { attrs, body ->
def link = g.remoteLink( attrs, body )
def fullLink = link.replace( grailsLinkGenerator.contextPath, grailsLinkGenerator.serverBaseURL )
out << fullLink.toString()
}
I need to convert it over to load/display the remote content in a ng-switch like this:
<div ng-switch-when='alpha' ><div alpha-directive></div></div>
So far I came up with this directive, but there must be a better way? Is there something like the grails link generator in AngularJS? I still need to pass in the ID to be appended to the URL.
app.directive('alphaDirective', function() {
var id = $scope.id;
var baseURL = "https://myServerURL/";
var controller = "admin";
var action = "alpha";
var path = "'" + baseURL + "/" + controller + "/" + action + "/" + id + "'";
return {
template: "<div ng-include=\"" + path + "\"></div>"
};
});
Upvotes: 0
Views: 408
Reputation: 27356
Well, generating the absolute path to a grails action isn't just a GSP
function. It's a Grails function. But you really don't want to be mixing up those two. Your Grails should be on the back end and your Angular should be on the front end and attempting to blur the two is going to end in maintenance hell.
So I'd recommend firstly, creating an endpoint using grailsLinkGenerator
. You pass in the name of the desired action
and it returns the full URL.
def absoluteLink(String action) {
// Return the absolute path for the action.
}
Then you can write an angular service with an API method like..
function getAbsoluteLink(action) {
// AJAX request to the server.
}
Then simply have the directive make the request to the service, and you've got a directive that can convert the name of an action into the full path, without needing to build up a String and without needing to mix up the responsibilities of your front end and your back end.
AND, if you decide to change the structure of your API, you won't need to change how the URL is created.
Upvotes: 2