简体   繁体   中英

How do i make jQuery datepicker work in angularjs with watch?

I am trying to use the jQuery datepicker in an angular program. I have a datepicker html which i use a couple of times.

If the user is changing the start time i want the end time to be a day later.

I defined the jquery datepicker with a class (tdate), it works fine but it doesnt tell the watch the date has changed so I tried adding an onSelect event that will make the watch notice the change. In the onSelect im applying the change so the watch notices BUT it always changes the scope where the class was made (for example here startTime was first so no matter if i change startTime or endTime the one that changes to the date selected would be startTime).

How can I make the onSelect event go to the current date-picker scope when its clicked? or any other way to solve the situation

Thanks!

DateMenu.html:

<date-picker ng-model="startTime"></date-picker>
<date-picker ng-model="endTime"></date-picker>

DateMenu.js:

$scope.$watch('startTime', function ) {
    // adds a day from the start time
    $scope.endTime = new Date($scope.startTime + (1 * 24 * 60 * 60 * 1000));
});

DatePicker.html:

<input type="text" class="tdate" ng-model="t.date">

DatePicker.js:

$('.tdate').datepicker({
    onSelect: function (text) {
        var time = text.split('/');
        // the safe apply makes the watch know theres a change in t.date
        $scope.$root.safeApply(function () {
            $scope.t.date = new Date(time[1] + '/' + time[0] + '/' + time[2]); 
        });
    }
});

var dateUpdated = function () {
    // changes in other parts of the program
    $scope.ngModel = $scope.t.date.getTime();
}

$scope.$watch('t.date', dateUpdated);

You can do something like this

HTML

<date-picker ng-model="t.date"></date-picker>

Script

.directive('datePicker', function(){
  return{
    restrict: 'E',
    link: function(scope, element, attributes){
      $('.tdate').datepicker({
          onSelect: function (selectedDate) {
              scope.ngModel = selectedDate;
              scope.$apply();
          }
      });
    },
    scope: {
      ngModel: '='
    },
    template: '<input type="text" class="tdate">'
  };
});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM