0

我在 AngularJS 中创建一个时间跟踪应用程序只是为了学习框架。我正在尝试通过单击“添加”按钮来创建在单个视图中添加多个计时器的能力。每个计时器显然都包含用于计时功能的独特属性和独特方法。我很难弄清楚如何设置服务来做这样的事情。任何帮助将不胜感激。

4

2 回答 2

1

正如@Chandermani 所提到的,您应该将计时器包装在指令中。这应该让你开始:

Javascript

app.controller('MainCtrl', function($scope) {
  $scope.timers = [];
})
.directive('timer', function() {
  return {
    restrict: 'E', 
    template: '<h1>{{counter}}s</h1>',
    controller: function($scope, $timeout) {
      $scope.counter = 0;

      var callback = function() {
        $scope.counter++;
        $timeout(callback, 1000);
      };

      $timeout(callback, 1000);
    }
  };
});

HTML

<body ng-controller="MainCtrl">
    <button ng-click="timers.push(1)">Add timer</button>
    <timer ng-repeat="timer in timers"></timer>
</body>

Plunker在这里

该指令将为数组中的每一项ng-repeat呈现指令的一个实例。在这个人为的示例中,该数组除了控制一次存在多少个计时器之外没有任何用途。您可以使用它来单独存储您可能拥有的有关每个计时器的任何信息。timertimers

于 2013-09-16T19:18:51.313 回答
0

You could create a control that manages a list of timers

var app = angular.module('myApp');

app.controller('TimerCtrl', function($scope) {
  $scope.timers = [];
  $scope.addTimer = function() {
    $scope.timers.push(new TaskTimer());
  };
  /* additional remove/clear/whatever functions attach to $scope */
});

Code example: http://jsfiddle.net/bonza_labs/qvnNa/

The "timer" object in the code example is something you would want to write yourself, so I've just stubbed it out with an object that doesn't actually do anything. As suggested, directives are a nice way to wrap up the rendering of the timers.

于 2013-09-16T20:06:51.260 回答