扩展Angular-UI Datepicker指令

时间:2016-03-09 15:17:15

标签: angularjs angularjs-directive angular-ui-bootstrap angular-ui-datepicker

我一直在使用Angular-ui-bootstrap中的ui-datepicker,但每次使用它时,我都需要设置它,就像我每次都这样做。 所以我想知道我是否可以创建一个名为custom-datepicker的指令,我可以使用

<custom-datapicker>

这样我就可以在指令中设置一次设置,然后在我的网站上的任何地方重复使用它。

我尝试创建一个类似下面的指令

app.directive('customDatapicker', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        templateUrl: function (elem, attrs) {
            return '/AngularJS/Directives/customDatapicker.html'
        },
        link: function (scope, element, attrs, ngModel) {
        $scope.inlineOptions = {
            showWeeks: true
        };

        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
        };


        $scope.open = function () {
            $scope.opened = true;
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[0];

        $scope.selected = {
            opened: false
        };

        },
});

我也在尝试使用模板,这样我就可以在它周围做一些自定义的html包装。到目前为止,除了样本html from

之外我什么都没有

TemplateHTML

<p class="input-group">
        <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="ngModel" is-open="selected.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open()"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>

在模板html中,我尝试通过执行ng-mode =&#39; ngModel&#39;来尝试在datepicker的ng-model中对我的指令输入模型进行绑定。 ,我认为这是正确的方式。

我在我的html页面中使用我的指令,其中数据是JS日期对象

<custom-datapicker ng-model='data'>

可以这样做吗?

2 个答案:

答案 0 :(得分:0)

不要在自定义指令上使用ng-model,而是定义自定义属性,然后将该值传递给datepicker的ng-model属性。

<custom-datepicker customAttrib="val" ...

然后在模板中:

<input ng-model="{{customAttrib}}" ...

答案 1 :(得分:0)

有趣的是,我今天一直在寻找一些非常相似的东西。你可以使用双向绑定传递你的模型,它主要起作用。

<my-datepicker ng-model="myDateModel"></my-datepicker>

指令:

scope: {
    ngModel: '='
}

模板:

<input type="text" ng-model="ngModel" />

问题在于,如果在使用datepicker之外操作模型,则指令上的模型类(ng-valid,ng-touching等)不会更新。输入和表单上的类做...