Search code examples
angularjscoffeescriptangularjs-ng-repeatrestangular

How to send the index of each iteration of an ng-repeat back to a factory?


I have a page of thumbnails using ng-repeat

<ul class="list-inline">
  <li ng-controller="IndicCtrl" ng-repeat="indic in indics" class="col-md-6 thumbnail">
    <linechart data="data" options="options" height="400"></linechart    >
  </li>
</ul>

I want each thumbnail to display a chart with its own data and I have this factory and 2 controllers. How can I get the value of indic.id sent to the function in show: so that it returns the corresponding data back to each thumbnail?

module.factory('Indic', [
 'Restangular', '$http'
 (Restangular, $http)->
   list: () -> Restangular.all('indics').getList()
   show: (indicId) -> Restangular.one('indics', indicId).get().then (chartData) ->
     $http.get(chartData.url, params: { 'api_key': chartData.api_key, 'series_id': chartData.series_id, 'num': chartData.num }).then (result) ->
       values = _.unzip result.data.series[0].data.reverse()
       dates = values[0]

       modDates = _.map dates, (x) ->
         new Date(x.replace(/(\d{4})(\d+)/, '$1-$2'))

       valueArray = values[1]

       data = []
       i = 0
       while i < dates.length
         data.push
           x: modDates[i]
           value: valueArray[i]
         i++
       return data
 ])

module.controller('IndicsCtrl', [
  '$scope', 'Indic'
  ($scope, Indic)->
    Indic.list().then((indics) ->
      $scope.indics = indics
      console.dir indics
  )
])

module.controller('IndicCtrl', [
  '$scope', 'Indic'
  ($scope, Indic)->
    Indic.show().then((data) ->
    $scope.indicId = indic.id
    $scope.data = data
    console.dir data
  )

Solution

  • this should be refactored to your own directive

    app.directive('myLinechart,['Indic',function(Indic) {
       return {
         restrict : 'E',
         scope : {
           indic : '='
         },
         link : function(scope) {
           scope.data = Indic.show(scope.indic.id);
         },
         template : ' <linechart data="data" options="options" height="400"></linechart    >';
       }
    }]);
    

    then you just modify your template

    <ul class="list-inline">
     <li ng-controller="IndicCtrl" ng-repeat="indic in indics" class="col-md-6 thumbnail">
      <my-linechart indic="indic"></my-linechart >
     </li>
    </ul>