AngularJS 如何加载模板宽度控制器并重新使用它?

AngularJS How can i load template width controller and reuse it?

我有这个代码:

<div class="mdl-cell mdl-cell--5-col mdl-shadow--4dp" style="margin-bottom:0;" ng-show="sub.view == 'fundoCaixa'">
    <div ng-if="sub.view=='fundoCaixa'" ng-controller="vender-fundoCaixa">
        <div ng-include="'views/vender/fundoCaixa.html'"></div>
    </div>
</div>

<div class="mdl-cell mdl-cell--5-col mdl-shadow--4dp" style="margin-bottom:0;" ng-show="sub.view == 'sangria'">
    <div ng-if="sub.view=='sangria'" ng-controller="vender-sangria">
        <div ng-include="'views/vender/sangria.html'"></div>
    </div>
</div>

<div class="mdl-cell mdl-cell--5-col mdl-shadow--4dp" style="margin-bottom:0;" ng-show="sub.view == 'apelido'">
    <div ng-if="sub.view=='apelido'" ng-controller="vender-apelido">
        <div ng-include="'views/vender/apelido.html'"></div>
    </div>
</div>

但是如果你看到它对所有子视图都是相同的规则,我需要重用它,我该怎么做?

<div class="mdl-cell mdl-cell--5-col mdl-shadow--4dp" style="margin-bottom:0;" ng-show="sub.view == '$var_here'">
    <div ng-if="sub.view=='$var_here'" ng-controller="$var_here">
        <div ng-include="'views/vender/$var_here.html'"></div>
    </div>
</div>

其中 $var_here 更改为要加载的上下文。

谢谢大家!

您不需要使用动态控制器。使用模板将代码放入指令中。您的代码可能如下所示(例如):

<div class="mdl-cell mdl-cell--5-col mdl-shadow--4dp" style="margin-bottom:0;" ng-show="sub.view == '$var_here'">
  <fundo-caixa ng-if="ctrl.fundoCaixa"></fundo-caixa>
  <sangria ng-if="ctrl.sangria"></sangria>
  <apelido ng-if="ctrl.apelido"></apelido>
</div>

每个指令都有自己的控制器(因此不需要动态分配它们)加上模板 url,这样就消除了 ng-include。 您可以尝试使用 ng-if 的方式。你想使用三个不同的变量并在控制器中分配它们true/false,还是像你的例子中那样进行检查。