title: Active Record or Data Mapper pattern for Angularjs?
body: <p>I'm very new to Angular, so hopefully I know enough to ask what seems like a reasonable design question.</p>
  
  <p>I'm charting some data via Angular, and am using $resource. Before bringing Angular in to the project I made a chart factory function for creating chart objects from sample json data I just pasted into the view.</p>
  
  <p>Now that I'm using Angular, it's tempting to put the charting functions into the 'Chart' resource, Active Record style, so that I have this one thing that can draw, save, update, etc.</p>
  
  <p>While the advantage of that pattern is simplicity, the drawback is coupling persistence with behavior. For example, it would be pretty awkward if I wanted to save chart settings to local storage.</p>
  
  <p>Having been bitten by AR enough times in my career already, I want to go with DM by leaving my chart object as-is, and having the controller pass data from the resource into my chart.</p>
  
  <p>However! My hazy understanding of angularjs' dependency injection suggests that I might be able to create a resource or some such that could accept a common persistence interface - is the right word a 'scope'?</p>
  
  <p>Example AR strategy:</p>
  
  <pre><code>App.factory('Chart', [
    '$resource', function($resource) {
      var chart = $resource('/api/charts/:id', {
        id: '@id'
      });
  
      chart.draw = function() { ... }
  
      return chart
    }
  ]);
  
  App.controller('ChartsCtrl', [
    '$scope', 'Chart', function($scope, Chart) {
      $scope.charts = Chart.query(function() {
        $.each($scope.charts, function(i, c) { c.draw() })
      })
    }
  ])
  </code></pre>
  
  <p>Example DM strategy:</p>
  
  <pre><code>App.chart = function(resource) {
    return { draw: function() { ... } }
  }
  
  App.factory('ChartResource', [
    '$resource', function($resource) {
      return $resource('/api/charts/:id', {
        id: '@id'
      })
    }
  ])
  
  App.controller('ChartsCtrl', [
    '$scope', 'ChartResource', function($scope, ChartResource) {
      $scope.charts = $.map(ChartResource.query(), function(i, resource) {
        chart = App.chart(resource)
        chart.draw()
        return chart
      }
    }
  ])
  </code></pre>
  
  <p>I think there is a third way, though, that I don't see because I don't quite grok how to leverage DI.</p>
  
  <p><strong>In other words, what's the AngularJS way to create an object with swappable persistence strategies?</strong></p>