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

88 views Asked by At

i have this code:

<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>

but if you see it is the same rule for all subviews, i need reuse it, how can i do it?

<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>

where there is $var_here change to context to load.

Thanks for all!

1

There are 1 answers

3
AmeRyoki On BEST ANSWER

You don't need to use dynamic controllers. Put your code into directives with templates. Your code could look like this (for example):

<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>

Each directive will have its own controller (so no need in assigning them dynamically) plus template url, so that eliminates ng-include. You can experiment with how you want to use ng-if. Do you want to use three different variables and assign them true/false in the controller, or do the check like you had in your example.