2

My application uses SpringMVC with apache velocity. Now I am going to add Angularjs controllers to the *.vm files(velocity files). I am finding a problem in accessing the objects set in the ModelAndView objects returned by the Spring controllers.

Can someone give me a simple example on how to do the same?

Example: Controller.java

ModelAndView mav = ControllerUtil.createModelView();
String dataSource = Constant.DATA_SOURCE;
HttpSession session = (HttpSession) mav.getModel().get("httpSession");  
**mav.addObject("dataSource", dataSource);**

Please give an example on how to get the 'dataSource' value inside the AngularJS module.

Thanks in Advance, DBKnot Team

user2230867
  • 93
  • 1
  • 3
  • I don't know much about SpringMVC, but is this topic relevant? http://stackoverflow.com/questions/13769732/angular-js-init-ng-model-from-default-values – koolunix Apr 08 '13 at 22:30

1 Answers1

2

I'm not familiar with velocity but I'm too trying to find a way to accomplish what you seem to be trying to do.

I'm currently exploring (tested it too) this approach. Use Jackson to parse your object into a String. This can either be done on the controller or in the JSP through a custom tag.

Example:

    ObjectMapper jsonMapper = new ObjectMapper();
    String result = null;
    try {
        result =  jsonMapper.writeValueAsString(obj);
    } catch (Exception e) {
        // Handle it
    }
    **mav.addObject("dataSource", result);**

On the HTML/JSP/Whatever have something like

<div ng-controller="MyCtrl" ng-init="init(${dataSource})">...</div>

and have your controller's init method handle the rest.

NOTE

As always you should read the documentation, and AngularJS recommends that the model should be initialized through AJAX requests, not obtained from the DOM (which is what happens here).

I would love to see alternatives to this

Hartimer
  • 525
  • 6
  • 20
  • One important thing to note, this strategy is very vulnerable. If your dataSource has quotes/double quotes in it you can run into trouble – Hartimer Apr 06 '13 at 23:13