2015-04-04 75 views
0

我想創建一個可隔離範圍的可重用的進度條指令。該指令將具有公共功能來啓動,停止和重置進度條。該指令將在ng-repeat訪問多個指令的隔離範圍

這裏使用的指令的定義:

chatApp.directive('jsProgress', function() { 

    var Stopwatch = function(options, updateCallback) { 

     // var timer  = createTimer(), 
      var offset, clock, interval; 

      // default options 
      options = options || {}; 
      options.delay = options.delay || 1; 


      // initialize 
      reset(); 

      function start() { 
      if (!interval) { 
       offset = Date.now(); 
       interval = setInterval(update, options.delay); 
      } 
      } 

      function stop() { 
      if (interval) { 
       clearInterval(interval); 
       interval = null; 
      } 
      } 

      function reset() { 
      clock = 0; 
      // render(0); 
      } 

      function update() { 
      clock += delta(); 
      // render(); 
      updateCallback(); 
      } 

      function delta() { 
      var now = Date.now(), 
       d = now - offset; 

      offset = now; 
      return d; 
      } 

      // public API 
      this.start = start; 
      this.stop = stop; 
      this.reset = reset; 
      this.update = update; 
     }; 



    return { 
     restrict : 'AE', 
     replace : true, 
     scope: { api: '=', key: '@'}, 
     template: '<div class="dot" ng-attr-id="dots"><ul id="{{key}}" data-currentState="2"><li class="dot-red"></li><li></li><li></li><li></li></ul></div>', 
     link : function($scope, elem, attr) { 

      var timer = new Stopwatch({delay: 5000}, updateCallback); 
      timer.start(); 
      function updateCallback() 
      { 
       var currentCount; 
       currentCount = $(elem).find('#' + $scope.key).attr('data-currentState'); 
       currentCount++; 
       $(elem).find('#' + $scope.key).attr('data-currentState',currentCount); 
       $(elem).find('#' + $scope.key+' li:nth-child(' + currentCount + ')').addClass('dot-red'); 

      } 

      $scope.api = 
      { 
        reset: function() 
        { 
         timer.reset(); 
        }, 

        start: function() 
        { 
         timer.start(); 
        }, 

        stop: function() 
        { 
         timer.stop(); 
        } 
       }; 

     } 
    }; 
}); 

這是怎麼會NG重複內使用

<js-progress api="api1" key="{{activeUserId}}_{{activeCompanyId}}" />

現在,我想ng-repeat中的指令的特定實例,並調用其公共API來啓動,停止和重置特定的進度條。我怎樣才能做到這一點?

+0

是,獲得實例,然後調用啓動功能 – 2015-04-04 19:20:25

+1

我添加了一個工作示例答案。 – 2015-04-04 20:10:08

回答

1

你可以嘗試這樣的事:

JS

// array of progress bars 
$scope.progressBars = [{id: 0}, {id: 1}]; 

// Call the api with the instance index, for example 
$scope.progressBars[0].start(); 

標記

<div ng-repeat="progressBar in progressBars track by $index> 
    <js-progress api="progressBars[$index]" key="{{activeUserId}}_{{activeCompanyId}}" /> 
</div> 

所以這裏的一點是,API屬性是通過每個重複不同的對象。

Plunker

+0

如何處理訂購?重新排序後,$索引不會被維護。我試圖使用api =「progressBars [{{activeUserId}}]但它說解析錯誤 – 2015-04-29 05:02:23