Last Updated: October 04, 2016
·
270
· tastycake

Preload Resources in Angular with Restangular

When writing data-intensive, front-end code, I like to cut down on as many server requests as possible. One way of doing this is writing the app's initial data to the page source itself. Angular can then automatically load this data on startup. There's a few ways of doing this, but I like to use a directive.

index.erb.html

<div ng-cloak preload-resource="<%= @items.to_json %>"></div>

preload-resource.js

angular.module('app')
 .directive('preloadResource', function preloadResourceDirective(Restangular) {
     return {
         link: function(scope,element,attrs) {
            scope.items = JSON.parse(attrs.preloadResource);
            element.remove();
     }
  };
});

When Angular comes across the preload-resource directive on the DOM, it executes the link function. I'm parsing the JSON and then assigning that collecting to $scope.items. Finally, the element is removed from the DOM.

Restangular

Restangular is a great Angular library for dealing with REST APIs. Restangular extends objects with a slew of features for working with a REST back-end. For my purposes, I just need to convert my list of records from the back-end (@items.to_json) into Restangular-enabled objects.

preload-resource.js

angular.module('app')
 .directive('preloadResource', function preloadResourceDirective(Restangular) {
     return {
         link: function(scope,element,attrs) {
            scope.items = JSON.parse(attrs.preloadResource);
            Restangular.restangularizeCollection(null, scope.items, 'items');
            element.remove();
     }
  };
});

And now I can update any of my items like so

var item = _.find($scope.items, {id: itemId});
item.done = true;
item.save();