You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

NgController.java 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2013 gitblit.com.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.gitblit.wicket.ng;
  14. import java.text.MessageFormat;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17. import org.apache.wicket.markup.html.IHeaderContributor;
  18. import org.apache.wicket.markup.html.IHeaderResponse;
  19. import com.google.gson.Gson;
  20. import com.google.gson.GsonBuilder;
  21. /**
  22. * Simple AngularJS data controller which injects scoped objects as static,
  23. * embedded JSON within the generated page. This allows use of AngularJS
  24. * client-side databinding (magic) with server-generated pages.
  25. *
  26. * @author James Moger
  27. *
  28. */
  29. public class NgController implements IHeaderContributor {
  30. private static final long serialVersionUID = 1L;
  31. final String name;
  32. final Map<String, Object> variables;
  33. public NgController(String name) {
  34. this.name = name;
  35. this.variables = new HashMap<String, Object>();
  36. }
  37. public void addVariable(String name, Object o) {
  38. variables.put(name, o);
  39. }
  40. @Override
  41. public void renderHead(IHeaderResponse response) {
  42. // add Google AngularJS reference
  43. response.renderJavascriptReference("bootstrap/js/angular.js");
  44. Gson gson = new GsonBuilder().create();
  45. StringBuilder sb = new StringBuilder();
  46. line(sb, MessageFormat.format("<!-- AngularJS {0} data controller -->", name));
  47. line(sb, MessageFormat.format("function {0}($scope) '{'", name));
  48. for (Map.Entry<String, Object> entry : variables.entrySet()) {
  49. String var = entry.getKey();
  50. Object o = entry.getValue();
  51. String json = gson.toJson(o);
  52. line(sb, MessageFormat.format("\t$scope.{0} = {1};", var, json));
  53. }
  54. line(sb, "}");
  55. response.renderJavascript(sb.toString(), null);
  56. }
  57. private void line(StringBuilder sb, String line) {
  58. sb.append(line);
  59. sb.append('\n');
  60. }
  61. }