0

使用 AngularJS 1.5,我构建了一个自定义属性指令,它向元素添加了一个 date-range-picker 指令及其选项:

app.directive('clSingleDatePicker', function($compile) {
    var opts_single_date = {
        singleDatePicker: true
    };
    return {
        restrict: 'A',
        compile: function compile(element, attrs) {
            element.attr('date-range-picker', '');
            element.attr('options', 'opts');
            element.removeAttr("cl-single-date-picker"); //remove the attribute to avoid indefinite loop
            return {
                pre: function preLink(scope, iElement, iAttrs, controller) {
                },
                post: function postLink(scope, iElement, iAttrs, controller) {
                    scope.opts = opts_single_date;
                    $compile(iElement)(scope);
                }
            };
        }
    };
});

当我将此指令添加到这样的简单输入时:

<input cl-single-date-picker type="text" ng-model="someModel"/>

我将在 DOM 中得到所需的结果:

<input type="text" ng-model="someModel" class="ng-pristine ng-valid ng-scope ng-isolate-scope ng-empty ng-touched" date-range-picker="" options="opts" style="">

并且日期范围选择器处于活动状态并且正在工作。但是,如果我向我的元素添加条件指令,在我的情况下是 ng-switch-when:

<input  ng-switch-when="1" cl-single-date-picker type="text" ng-model="someModel"/>

即使正在执行指令函数,该元素也不会被渲染。如何将我的指令添加到带有条件指令的元素并渲染它?

一个可行的解决方案(已编辑) 通过添加高于 ng-switch 的优先级值(显然是 1200 ),customed 指令现在在 ng-switch-then 指令之前执行,并且正在呈现 datepicker。

4

1 回答 1

0

编辑:误解了这个问题

看起来 theng-switch-when也被应用于属性指令,但它要么认为它不在 an 内,ng-switch要么它无权访问外部范围,因此ng-switch-when解析为false.

有几个解决方案:

1) 把inputa 包起来,span然后把它ng-switch-when放在上面而不是input

2)删除ng-switch-when指令中的属性element.removeAttr("ng-switch-when");

两者似乎都有效(在 Plunker 中进行实验时)。就个人而言,我更喜欢第一个,因为它都在模板中。


原答案:

ng-switch影响它所在的​​元素,而不是其中的属性。有几种方法可以有条件地显示自定义属性:

如果你想使用ng-switch,你可以有两个输入:

<input ng-switch-when="1" cl-single-date-picker type="text" ng-model="someModel"/>
<input ng-switch-when="2" type="text" ng-model="someModel"/>

或者,您可以在指令上添加一个额外的属性并在指令中进行检查,例如

<input cl-single-date-picker show-picker="{{showPicker}}" type="text" ng-model="someModel"/>

您也可以使用来有条件地应用属性(请参阅此问题)。我自己没有试过这个。

于 2018-11-07T12:20:37.757 回答