0

Есть таймер для обратного отсчета времени. Как только время закончилось - он останавливается. Вот код.

(function(){
    "use strict";

    angular.module('app').controller('ExamTaskController', ExamTaskController).directive('testTimer', testTimer);

    testTimer.$inject = ['$interval', 'dateFilter'];

    function testTimer($interval, dateFilter) {
        return {
            scope:{
                currentTime: "="
            },
            link: function(scope, element, attrs) {
                var stopTime, interval, countSeconds, stop;

                function updateTime() {
                    var date = new Date(interval)
                    date.setHours(date.getHours() - new Date().getHours());
                    date.setMinutes(date.getMinutes() - new Date().getMinutes());
                    date.setSeconds(date.getSeconds() - new Date().getSeconds());
                    countSeconds = date.getSeconds() + date.getMinutes() * 60 + date.getHours() * 3600;
                    scope.currentTime=date;

                    if (countSeconds != 0) {
                        element.text(dateFilter(date, 'H:mm:ss'));
                    } else {
                        element.text(dateFilter(date, 'H:mm:ss'));
                        stop();
                    }
                }
                scope.$watch(attrs.testTimer, function(value) {
                    interval = value;
                    updateTime();
                });

                stopTime = $interval(updateTime, 1000);

                stop = function() {
                    if (angular.isDefined(stopTime)) {
                        $interval.cancel(stopTime);
                        stopTime = undefined;
                    }
                };

                scope.$on('$destroy', function() {
                    stop();
                });
            }
        }
    }
})();

Вот его представление

<h4 > Оставшееся время: <span test-timer="{{vm.leadTime}}" current-time="{{vm.currentTime}}" ></span></h4>

Значение {{vm.leadTime}}, которое передается в директиву является текущей датой.

(function(){
    'use strict';
    angular.module('app').controller('ExamTaskController', ExamTaskController);
    ExamTaskController.$inject = ['ExamService', '$location', 'localStorageService', '$timeout', '$filter'];
    function ExamTaskController(ExamService, $location, localStorageService, $timeout, $filter){
        var vm = this;
        vm.activate = function(){
            vm.leadTime = null;
 vm.currentTime = null;
            vm.start=new Date;
                var date = new Date(vm.start);
                date.setMinutes(date.getMinutes() + localStorageService.get('examObject').leadTime);
                vm.leadTime = date;
}
        vm.activate();
    }
})();

Вопрос: как можно уже просчитанное значение времени передать в контроллер?

1
  • Кстати, если у вас все вдруг перестает вообще работать, можно заглянуть в консоль - наверняка там будет ошибка. В вашем случае в консоли писалась ошибка. 18 сен 2017 в 6:20

1 ответ 1

0

Можно решить разными путями, но лучший - двухсторонний биндинг.

Пример на jsfiddle

angular.module('ExampleApp', [])
  .controller('ExampleController', [function() {
    this.leadTime = new Date(Date.now() + 50000);
    this.currentTime = null;
  }]).directive("testTimer", testTimer);
testTimer.$inject = ['$interval', 'dateFilter'];

function testTimer($interval, dateFilter) {
  return {
    scope: {
      currentTime: "="
    },
    link: function(scope, element, attrs) {
      var stopTime, interval, countSeconds, stop;

      function updateTime() {
        var date = new Date(interval)
        date.setHours(date.getHours() - new Date().getHours());
        date.setMinutes(date.getMinutes() - new Date().getMinutes());
        date.setSeconds(date.getSeconds() - new Date().getSeconds());
        countSeconds = date.getSeconds() + date.getMinutes() * 60 + date.getHours() * 3600;
        scope.currentTime = date;
        if (countSeconds != 0) {
          element.text(dateFilter(date, 'H:mm:ss'));
        } else {
          element.text(dateFilter(date, 'H:mm:ss'));
          stop();
        }
      }
      scope.$watch(attrs.testTimer, function(value) {
        interval = value;
        updateTime();
      });

      stopTime = $interval(updateTime, 1000);

      stop = function() {
        if (angular.isDefined(stopTime)) {
          $interval.cancel(stopTime);
          stopTime = undefined;
        }
      };

      scope.$on('$destroy', function() {
        stop();
      });
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">
    <h4> Оставшееся время: <span test-timer="{{vm.leadTime}}" current-time="vm.currentTime"></span></h4>
    <h4> Оставшееся время в директиве: {{vm.currentTime|date:'H:mm:ss'}}</h4>
  </div>
</div>

UPDATED

Ваш пример на jsfiddle.

Обратите внимание на передачу параметра currentTime в директиву, а именно на {{}}.

0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.