Angular UI Date Plugin:On Select不起作用

时间:2015-02-24 11:03:13

标签: javascript angularjs

我正在使用AngularJS的datepicker插件。我有两个目标尚未达到:

  1. 点击日期后执行操作(请参阅app.directive 下文)。

  2. 不在指令声明中执行此操作,而是在特定控制器内执行此操作:app.controller('dateCtrl', ...)

  3. 我的代码来了:

    HTML:

    <div ng-app="MyApp">
    
       <div ng-controller="someOtherCtrl"> ... </div>
    
       <div ng-controller="dateCtrl">
    
          <p>Pick date:</p>
    
          <input type="text" ng-model="date" ui-date="dateOptions" ui-date-format="yy-mm-dd" custom-datepicker/>
    
       </div>
    
       <div ng-controller="someOtherCtrl"> ... </div>
    
    </div>
    

    我的JS:

    var app = angular.module('myApp', ['ui.date']);
    
    app.controller('dateCtrl', function($rootScope, $scope) {
            $scope.dateOptions = {
                dateFormat:'DD, d  MM yy',
                minDate: 0,
                maxDate: "+6M"
            };
    
            /* How can I access the on-select-method of my datepicker here inside this controller? */
    });
    
    app.directive("customDatepicker", function () {
        return {
            restrict: "A",
            require: "ngModel",
            link: function (scope, elem, attrs, ngModelCtrl) {
                elem.datepicker({
                    onSelect: function (dateText) {
                        ngModelCtrl.$setViewValue(dateText);
                        scope.$apply();
                        /* This alert does not work: */
                        alert('i want this to be triggered, but it does not work');
                    }
                });
            }
        }
    });
    

    单击日期时,不会触发警报。为什么?我如何调整代码?

    为了在app.controller声明中触发此选择操作,我需要做些什么?

1 个答案:

答案 0 :(得分:0)

这是我的angularjicker for angularjs的代码,希望这对你有用。 HTML

<div ng-app="myApp">
  <div ng-controller="dateCtrl">

    <label>Date : </label>
    <input ng-model="date" ui-date>
    <hr>
      <h1>  {{date | date: 'dd/MM/yyyy'}}</h1>
  </div>
</div>

Js Code

var myApp = angular.module('myApp', []);

myApp.directive('uiDate', function() {
    return {
      require: '?ngModel',
      link: function (scope, elem, attrs, ngModelCtrl) {
            elem.datepicker({
                onSelect: function (dateText) {
                    ngModelCtrl.$setViewValue(dateText);
                    scope.$apply();
                    /* This alert does not work: */
                    alert('i want this to be triggered, but it does not work');
                }
            });
        }
    };
  });

myApp.controller('dateCtrl', function($rootScope, $scope) {
        $scope.dateOptions = {
            dateFormat:'DD, d  MM yy',
            minDate: 0,
            maxDate: "+6M"
        };

        /* How can I access the on-select-method of my datepicker here inside this controller? */
});

这里正在使用jsFiddle Link