使用角度计时器停止个人计时器

时间:2015-10-10 12:11:13

标签: angularjs timer

我有一个使用Angular Timer的应用,但我无法停止单个计时器。当我点击第一个超时时,计时器会停止它们。

基本上,我根据员工的姓名制作个人计时器,如下所示:

的index.html

...
<md-card class="md-padding">
  <md-content-card>
  <md-input-container>
    <label>Employee</label>
    <md-select ng-model="employeeName">
      <md-option ng-repeat="employee in employees" value="{{employee.name}}">
        {{employee.name}}
      </md-option>
    </md-select>
  </md-input-container>
  <center>
  <md-button class="md-raised md-primary md-hue-2" ng-click="startTimer()">Time In</md-button>
  </center>
  </md-content-card>
</md-card>

<md-card ng-repeat="(key, value) in times">
  <md-content-card>
  <center>
    <h2>{{ value.employeeName }}</h2>
    <h3>Time In At: {{ value.date | date: 'medium' }}</h3>
    <h3>
      <timer interval="1000">{{hours}} hour{{hoursS}}, {{minutes}} minute{{minutesS}}, {{seconds}} second{{secondsS}}.</timer>
    </h3>
  <br>
  <md-button class="md-raised md-accent md-hue-2" ng-click="stopTimer()">Time Out</md-button>
  </center>
  </md-content-card>
</md-card>
...

app.js

angular
  .module("HomeApp")
  .controller("HomeCtrl", function ($scope){
    $scope.employees = [
      {name: "Jerald"},
      {name: "Arnie"},
      {name: "Junnie"},
      {name: "Gilbert"}
    ];

    $scope.times = [];

    $scope.startTimer = function (){
        $scope.times.push({
          employeeName: $scope.employeeName,
      date: new Date()   
        });
    };

    $scope.stopTimer = function (){
        $scope.$broadcast('timer-stop');
    };

    $scope.$on('timer-stopped', function (event, data){
        console.log('Timer Stopped - data = ', data);
    });

  });

enter image description here

1 个答案:

答案 0 :(得分:2)

Angular计时器基于在控制器范围内引发的事件。如果在单个范围上定义了多个计时器,则所有计时器都会一起启动和停止。

你很幸运,因为你在这里使用ng-repeat来创建一个新范围,并且计时器嵌套在其中。

您只需访问此范围即可引发停止特定计时器的事件。 当调用按钮的事件处理程序this指向ng-repeat的范围时,这样可以正常工作

  $scope.stopTimer = function (){
        this.$broadcast('timer-stop');
    };