【问题标题】:Angular JS - adding a custom directive to an element with ng-switch-when directiveAngular JS - 使用 ng-switch-when 指令向元素添加自定义指令
【发布时间】:2018-11-07 11:56:11
【问题描述】:

使用 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 apparently),customed 指令现在在 ng-switch-then 指令之前执行,并且正在呈现 datepicker。

【问题讨论】:

标签: javascript angularjs angularjs-directive ng-switch angularjs-ng-switch


【解决方案1】:

编辑:误解了问题

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

有几个解决方案:

1) 将input 包裹在span 中,并将ng-switch-when 放在上面而不是input

2) 移除指令element.removeAttr("ng-switch-when");中的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"/>

或者,您可以在指令上add an extra attribute 并在指令中进行检查,例如

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

您还可以使用this 有条件地应用该属性(请参阅this question)。我自己没试过。

【讨论】:

  • 谢谢,Sophie,但这不是我的意思——我的问题是当元素有 ng-switch-当与我的指令结合时,它根本不会出现。
  • 啊抱歉,我误解了这个问题!
  • 一个稍微笨拙的解决方案(但可能是最简单的)可能是将输入包装在 span 中,然后将 ng-switch-when 放在上面而不是输入。
  • @AgentZmith 我已经编辑了我的答案。希望对您有所帮助!
  • 是的@Sophie,这可能是我将采用的解决方案(选项 1),谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2017-08-27
  • 2013-10-17
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多