Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

javascript - Angular JQuery Datepicker Not Setting MinDate on Load

I'm using JQuery UI's Datepicker on Date From and Date To fields in an AngularJS project. I've added the directive to bind the value to the model value, and I've also added a check to OnSelect that sets the minDate and maxDate options for each field (so the Date To is never earlier than the Date From). The problem is that, on loading the page, no date has actually been selected (even though the model has a value), so it is still possible to select a To date earlier than the Date From. I added a $watch service to at least correct the error, but I still can't figure out how to set the minDate on load either within the directive or inside the controller. I've also tried $(document).ready outside of the Angular code, but that isn't working either. Here's my code prior to adding anything to set the minDate.

Within controller:

$scope.messagesForm.dateFrom = moment().subtract('days', 30).format('MM/DD/YYYY');
$scope.messagesForm.dateTo = moment().format('MM/DD/YYYY');
$scope.$watch('messagesForm.dateTo', function(newVal, oldVal) {
    if (!newVal) return;
    if (Date.parse(newVal) < Date.parse($scope.messagesForm.dateFrom)) {
        $scope.messagesForm.dateFrom = newVal;
    }
});

Directive:

.directive('datepicker', function() {
return {
    restrict: 'A',
    require : 'ngModel',
    link : function (scope, element, attrs, ngModelCtrl) {
        $(function(){
            element.datepicker({
                dateFormat: 'mm/dd/yy',
                showStatus: true,
                showWeeks: true,
                highlightWeek: true,
                maxDate: 0,
                numberOfMonths: 1,
                showAnim: "scale",
                showOptions: { origin: ["bottom", "right"] },
                onSelect: function (date) {
                    if (this.id === "MessageDateFrom") {
                       $("#MessageDateTo").datepicker("option", "minDate", date);
                    } else if (this.id === "MessageDateTo") {
                        $("#MessageDateFrom").datepicker("option", "maxDate", date);
                    }
                    ngModelCtrl.$setViewValue(date);
                    scope.$apply();
                }
            });
        });
    }
}

});

HTML:

<div class="form-group">
     <input type="text" id="MessageDateFrom" class="form-control dates" ng-model="messagesForm.dateFrom" datepicker readonly="readonly" />
</div>
<div class="form-group">
     <input type="text" id="MessageDateTo" class="form-control dates" ng-model="messagesForm.dateTo" datepicker readonly="readonly" />
</div>

Failing JQuery I've attempted:

$(document).ready(function() {
    $("MessageDateTo").datepicker("option","minDate",$("MessageDateFrom").val());
};

Any ideas?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need to worries about when controller loads or what just add this two property which is minDate & maxDate with there limit like minDate:"-30d",maxDate: 0,

You also can place minDate and maxDate values dynamically from directive property.

Directive

app.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ngModelCtrl) {
            $(function(){
                element.datepicker({
                    dateFormat: 'mm/dd/yy',
                    showStatus: true,
                    showWeeks: true,
                    highlightWeek: true,
                    minDate:"-30d", //here i did logic -30d
                    maxDate: 0, //today is max date
                    numberOfMonths: 1,
                    showAnim: "scale",
                    showOptions: { origin: ["bottom", "right"] },
                    onSelect: function (date) {
                        ngModelCtrl.$setViewValue(date);
                        scope.$apply();
                    }
                });
            });
        }
    }
});

Working Plunkr

Update

Sorry for my wrong assumption, If you really do care about whenever the data gets loaded or date variable are assigned at that time jquery ui datepicker should bind to them, then I'll prefer to use attrs.$observe which will gets call whenever your attribute expression gets evaluated. For make it working I did added one attribute name loaded="{{messagesForm.dateFrom}}" & loaded="{{messagesForm.dateTo}}" on the page so whenever the value gets assigned to dateFrom and dateTo the respective datepicker will get assign to their elements

Directive

 app.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ngModelCtrl) {
            //get called when `{{}}` value evaluated
            attrs.$observe('loaded',function(val){
              element.datepicker({
                  dateFormat: 'mm/dd/yy',
                  showStatus: true,
                  showWeeks: true,
                  highlightWeek: true,
                  maxDate: 0,
                  numberOfMonths: 1,
                  showAnim: "scale",
                  showOptions: { origin: ["bottom", "right"] },
                  onSelect: function (date) {
                      if (this.id === "MessageDateFrom") {
                         $("#MessageDateTo").datepicker("option", "minDate", date);
                      } else if (this.id === "MessageDateTo") {
                          $("#MessageDateFrom").datepicker("option", "maxDate", date);
                      }
                      ngModelCtrl.$setViewValue(date);
                      scope.$apply();
                  }
              });
            })

        }
    }
});

Updated Plunkr with demonstration of setting value of scope variables after 5 sec.

Hope this could help you, Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...