2015-04-04 76 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