1

So I have a ternary operator test in my angularJS code to determinate which variable to use on a repeat block, but this test is being done many times inside it and I think this is dumb. Is there a way to store the expression result in a variable and use it instead of repeating the expression?

The code:

<tr ng-repeat="meta in metas">
    <td class="mdl-data-table__cell--non-numeric">
        {{meta.admMetNome}} <span class="pull-right">{{meta.pagCidadesPagCid[0].pagCidId ? usuarios[meta.pagCidadesPagCid[0].pagCidId].qtd : usuarios['total'].qtd}} / {{meta.admMetValor}}</span>
        <md-progress-linear md-mode="determinate" value="{{(meta.pagCidadesPagCid[0].pagCidId ? usuarios[meta.pagCidadesPagCid[0].pagCidId].qtd : usuarios['total'].qtd) * 100 / meta.admMetValor}}"></md-progress-linear>
        {{(meta.pagCidadesPagCid[0].pagCidId ? usuarios[meta.pagCidadesPagCid[0].pagCidId].qtd : usuarios['total'].qtd) * 100 / meta.admMetValor | number:2}}% - Prazo: de {{meta.admMetInicio | date: 'dd/MM/yyyy'}} a {{meta.admMetFim | date: 'dd/MM/yyyy'}}
    </td>
</tr>
1
  • 1
    Would be a good use case for a directive or component. Would take the business logic out of the view Commented Jan 21, 2017 at 13:27

2 Answers 2

1

Something like this in your controller should do the trick(assuming 'usuarios' is a scoped var). But like @charlietfl suggested would be a good opportunity for a directive.

$scope.assignValue = function(meta) {
  return (meta.pagCidadesPagCid[0].pagCidId) ? usuarios[meta.pagCidadesPagCid[0].pagCidId].qtd : usuarios.total.qtd * (100 / meta.admMetValor);
};
<tr ng-repeat="meta in metas">
  <td class="mdl-data-table__cell--non-numeric">
    {{meta.admMetNome}} <span class="pull-right">{{meta.pagCidadesPagCid[0].pagCidId ? usuarios[meta.pagCidadesPagCid[0].pagCidId].qtd : usuarios['total'].qtd}} / {{meta.admMetValor}}</span>
    <md-progress-linear md-mode="determinate" value="assignValue(meta)">
    </md-progress-linear>
    {{(meta.pagCidadesPagCid[0].pagCidId ? usuarios[meta.pagCidadesPagCid[0].pagCidId].qtd : usuarios['total'].qtd) * 100 / meta.admMetValor | number:2}}% - Prazo: de {{meta.admMetInicio | date: 'dd/MM/yyyy'}} a {{meta.admMetFim | date: 'dd/MM/yyyy'}}
  </td>
</tr>
Sign up to request clarification or add additional context in comments.

Comments

1

In controller object or in $scope create a function with a parameter to pass your meta in it. Like getValue(meta). And simply return your ternary operator in it. Then just use this function in the expression: value={{$ctrl.getValue(meta)}}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.