【问题标题】:ng-switch with shared options带有共享选项的 ng-switch
【发布时间】:2014-10-12 13:29:58
【问题描述】:

我有一个要重构的 ng-switch 语句。它看起来像这样:

<div ng-switch on="property.type">
    <input type="text" ng-switch-when="string" ng-model="property.value" placeholder="Property value">
    <select ng-switch-when="bool" ng-model="property.value" ng-options="value for value in [true,false]" placeholder="Property value"></select>
    <input type="number" ng-switch-when="int" ng-model="property.value" placeholder="Property value">
    <input type="text" ng-switch-default ng-model="property.value" placeholder="Property value">
</div>

您会注意到ng-modelplaceholder 选项在所有情况下都相同。我的问题是:我可以以某种方式重构它以使这些选项只编写一次吗?

谢谢!乌里

【问题讨论】:

    标签: angularjs refactoring ng-switch


    【解决方案1】:

    虽然没有完全重构以避免所有重复,但您可以通过组合输入标签来减少一点:

    <div ng-switch on="property.type">
      <select ng-switch-when="bool" ng-model="property.value" ng-options="value for value in [true,false]" placeholder="Property value"></select>
      <input type="{{property.type == 'int' ? 'number' : 'string'}}" ng-switch-default ng-model="property.value" placeholder="Property value">
    </div>
    

    这可以在http://plnkr.co/edit/FybDC1I4U7rSC6GZJ3az看到

    如果这是我正在做的一个项目,我怀疑我不会进一步重构它,留下少量重复标记,以保持清晰。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2016-07-08
      • 2016-01-24
      • 1970-01-01
      • 2018-11-11
      相关资源
      最近更新 更多