Last Updated: February 25, 2016
·
1.101K
· ique

Cheating with AngularJS

I'm new to AngularJS, and while I know that you should load all your data through a JSON API on your back-end, I also had an existing Rails project that I wanted to drop in AngularJS just for the easy (and awesome) data-bindings.

But server-side rendering of all the data was already in place, and I didn't want to change up my whole back-end architecture.

The way for me to work around this issue (which I'm quite sure would be frowned-upon, but works) was to access the scope on DOM Ready and then call a controller-function to add data with the server-side rendered data.

The following code is what I added to the page where @data is the data brought over from server-side.

 <script type="text/javascript">
    // Load all the data brought over from server-side
  $(function() {
      var _scope = angular.element($("#controllerDiv")).scope();
      _scope.$apply(function(scope) {
        <% @data.each do |item| %>
          scope.addItem({
            item_name: "<%= item.name %>",
            weight: <%= item.weight %>
          });
        <% end %>
        });
      });
</script>

In this example, the controller that has the function addItem is attached to the div with the id #controllerDiv.

2 Responses
Add your response

Spooky.
Of course I haven't seen how is your code organized, but I would prefer to have service for that. Behind service you can hide this particular implementation, that would be easily changed if you want use REST later.

over 1 year ago ·

The problem is that I would still need to declare that service inside the HTML template and not in the JS file, since I can't do server-side rendering in the JS file.

Though of course all of this will, before it sees production, be refactored to use a proper REST API in the back-end.

over 1 year ago ·