【问题标题】:How to pass controller Function variable to Datepicker Directive?如何将控制器函数变量传递给 Datepicker 指令?
【发布时间】:2018-07-19 14:13:17
【问题描述】:

我是 Angularjs 的新手。我放了 2 个日期选择器。我需要当我从第一个日期选择器中选择日期时,应该在第二个日期选择器中禁用该日期的较小日期。我无法为第二个 Datepicker 指令设置“minDate”。

下面是我的代码:

HTML 代码:

<div ng-controller='TestController'>

  <label>From Date :</label>
  <input type="text" id="1" datepicker="" ng-init="variable=''"
         ng-model="startDate" ng-change="test()" />

  <label>To Date :</label>
  <input type="text" id="2" callFuc="test()" datepicker1=""
         ng-model="endDate" />
</div>

JS代码:

app.controller('TestController', function($scope, $window) {
  $scope.test = function() {
    $scope.variable = $scope.startDate;
    $window.alert("From date is" + $scope.variable);
  };
});

app.directive('datepicker', function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attr, ngModel) {
      $('#1').datepicker({
        minDate: 0,
        onSelect: function(dateText) {
          scope.$apply(function() {
            ngModel.$setViewValue(dateText);
          });
        }
      });
    }
  };
});

app.directive('datepicker1', function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attr, ngModel) {
      $('#2').datepicker({
        minDate: scope.test(),
        onSelect: function(dateText) {
          scope.$apply(function() {
            ngModel.$setViewValue(dateText);
          });
        }
      });
    }
  };
});

我可以使用 minDate : "0" 在第一个 Datepicker 中禁用过去的日期。
但我无法为第二个 Datepicker 正确设置 minDate。我无法从第一个 Datepicker 中获取选定的日期并将其传递给“datepicker1”指令。任何帮助或建议将不胜感激。


更新

我已经更新了代码。请检查它。

https://plnkr.co/edit/ohCFzpwLGgFPPH49jybq?p=preview

【问题讨论】:

  • 代码使用了哪个 jQuery datepicker 库?
  • jquery ui datepicker

标签: angularjs angularjs-directive jquery-ui-datepicker


【解决方案1】:

datepicker 指令需要监视更改并根据需要更新 minDate

app.directive('datepicker1', function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attr, ngModel) {
      scope.$watch(attr.minDate, function(value) {    
          el.datepicker({
            minDate: value,
            onSelect: function(dateText) {
              scope.$apply(function() {
                ngModel.$setViewValue(dateText);
              });
            }
          });
      });
    }
  };
});

用法:

  <label>To Date :</label>
  <input type="text" min-date="variable" datepicker1
         ng-model="endDate" />

【讨论】:

  • 感谢您的信息。我试过这段代码。根据从第一个日期选择器更改的日期,值是正确的。但是对于第二个日期选择器,所有日期都将启用。似乎 minDate 没有得到那个值
  • 下一步是创建一个PLNKR 来重现问题。
  • 我已经更新了代码。请审查它。 plnkr.co/edit/ohCFzpwLGgFPPH49jybq?p=preview
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
相关资源
最近更新 更多