Search code examples
javascriptjqueryangularjshtml

how to use timepicker more than once


I have 2 controllers for setting time , and I have a javascript method linked to 1 of the controllers. I just want to know how to use this method for 2 controllers with 2 different id. Thanks

var timepicker = new TimePicker('time1', {
    lang: 'en',
    theme: 'dark'
});
timepicker.on('change', function (evt) {
    var value = (evt.hour || '00') + ':' + (evt.minute || '00');
    evt.element.value = value;
});

HTML

<div class="col-md-2">
    <div class="form-group">
        <label class="title_lable">From:</label>
        <input id="time1" type="text" class="form-control input-sm" ng-model="from">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group">
        <label class="title_lable">To:</label>
        <input id="time2" type="text" class="form-control input-sm" ng-model="to">
    </div>
</div>
<script src="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
<link href="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>

And how to capture the value in an angularjs $scope Thanks in advance


Solution

  • Just read the documentation about it: https://github.com/jonataswalker/timepicker.js

    You need to use the array syntax to use multiple elements. Then, you could store the times in an object.

    See this working snippet:

    var times = {}; // Added to initialize an object
    
    var timepicker = new TimePicker(['time1', 'time2'], {
      theme: 'dark',
      lang: 'en'
    });
    
    timepicker.on('change', function(evt){
      var value = (evt.hour || '00') + ':' + (evt.minute || '00');
      evt.element.value = value;
      
      //Added the below to store in the object and consoling:
      var id = evt.element.id;
      times[id] = value;
      console.clear();
      console.log(times); // Display the object
    });
    <link href="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css"  rel="stylesheet">
    <script src="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
    
    <div class="col-md-2">
      <div class="form-group">
        <label class="title_lable">From:</label>
        <input id="time1" type="text" class="form-control input-sm" ng-model="from">
      </div>
    </div>
    <div class="col-md-2">
      <div class="form-group">
        <label class="title_lable">To:</label>
        <input id="time2" type="text" class="form-control input-sm" ng-model="to">
      </div>
    </div>