AngularJS-如何刷新指令范围



我已经创建了一个具有"选项"的简单datepicker指令。

因此,我以一组选项启动datepicker,然后由于业务逻辑,我更改了这些选项,但这并没有刷新。

在此示例中,我需要将"终结"的datepicker启动日期更新到与" startdate"同一日期。

这是我的代码:

指令:

function datepicker() {
    return {
        restrict: "A",
        scope: {
            options : '='
        },
        link: function(scope, element, attrs) {
            var opts = scope.options || {};
            element.datepicker({
                keyboardNavigation: false,
                forceParse: false,
                autoclose: true,
                useCurrent: true,
                format: opts.format || 'dd/mm/yyyy',
                startDate : opts.startDate || ''
            });
        }
    };
}

控制器:

$scope.evaluation = {};
$scope.startDatepickerOptions = {
    startDate : new Date()
};
$scope.endDatepickerOptions = {
    startDate : new Date()
};
$scope.$watch('evaluation.startDate', function(newValue) {
    $scope.endDatepickerOptions.startDate = newValue;
});

查看:

<input type="text" ng-model="evaluation.startDate" name="startDate" datepicker options="startDatepickerOptions"/>
<input type="text" ng-model="evaluation.endDate" name="endDate" datepicker options="endDatepickerOptions"/>

,这是解决方案:

我需要在指示链接功能上添加平等观察器。到目前为止,由于日期/字符串问题,我已经实施了时刻。

这是最终代码:

指令(链接功能)

link: function(scope, element, attrs) {
    var opts = scope.options || {};
    element.datepicker({
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        useCurrent: true,
        format: opts.format || 'dd/mm/yyyy',
        startDate : opts.startDate || ''
    });
    scope.$watch('options.startDate', function(newValue) {
        if(newValue) {
            element.datepicker('setStartDate', newValue);
            element.datepicker('setDate', "");
        }
    });
}

控制器

$scope.startDatepickerOptions = {
    startDate : moment().toDate()
};
$scope.endDatepickerOptions = {
    startDate : moment().toDate()
};
$scope.$watch('evaluation.startDate', function(newValue) {
    if(newValue)
        $scope.endDatepickerOptions['startDate'] = moment(newValue, "DD-MM-YYYY").toDate();
});

最新更新