【问题标题】:Setting angular directive name via model value通过模型值设置角度指令名称
【发布时间】:2016-05-04 18:21:45
【问题描述】:

我有一个循环,我需要根据值指定一个特定的指令。这是我所拥有的:

<div ng-repeat="w in row.widgets" class="col-md-{{12/row.widgets.length}}">
                    <{{w.type}}>
                    </{{w.type}}>
                </div>

问题是,我已经设置了匹配的指令,但是并没有实际调用指令,标记输出很简单

<widget-directive-one>
<widget-directive-two>
<widget-directive-three>

我不明白为什么它不会调用同名指令而不是输出实际值。任何建议将不胜感激!

【问题讨论】:

    标签: javascript angularjs angular2-directives


    【解决方案1】:

    属性名称和标签名称不能在 dom 本身(视图)中动态生成。

    Angular 需要能够解析 dom 中的元素并将现有标签名称或属性与这些指令进行比较

    有很多方法可以解决这个问题...ng-switchng-if 或返回您想要的指令标记的自定义指令是几个示例

    【讨论】:

      【解决方案2】:

      为你的控制器 $scope 添加一个 widgetType。然后你可以这样做:

      <div ng-switch="widgetType">
        <widget-one ng-switch-when="widgetOne"></widget-one>
        <widget-two ng-switch-when="widgetTwo"></widget-two>
        <widget-three ng-switch-when="widgetThree"></widget-three>
      </div>
      

      【讨论】:

        【解决方案3】:

        使用这个ng-if

        <div ng-repeat="w in row.widgets" class="col-md-{{12/row.widgets.length}}">
            <widget-directive-one ng-if="$index==0"></widget-directive-one>
            <widget-directive-two ng-if="$index==1"></widget-directive-two>
            <widget-directive-three ng-if="$index==2"></widget-directive-three>
        </div>
        

        【讨论】:

          【解决方案4】:

          使用ng-bind-html 指令:

          来自文档:

          ngBindHtml

          评估表达式并将生成的 HTML 以安全的方式插入到元素中。

          您也可以绕过对您知道是安全的值的清理。为此,请通过$sce.trustAsHtml 绑定到明确信任的值。请参阅Strict Contextual Escaping (SCE) 下的示例。

          -- AngularJS ng-bind-html Directive API Reference

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-10-08
            相关资源
            最近更新 更多