Reputation: 172
I have an app using Angular Timer though I'm having trouble stopping a single timer. When I click timeout on the first, timer it stops them all.
Basically, I make individual timer base on the name of an employee as follows:
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);
});
});
Upvotes: 0
Views: 1379
Reputation: 42669
Angular timer is based on the event raised on the scope of controller. If there are multiple timers defined on a single scope all of then get started and stopped together.
You are lucky here as you are using ng-repeat
here which creates a new scope, and the timer is nested inside it.
You just need to access this scope to raise events that stop the specific timer.
When the event handler for the button is called this
points to the scope of the ng-repeat
so this works
$scope.stopTimer = function (){
this.$broadcast('timer-stop');
};
Upvotes: 2