3

I need to execute an expression inside ng-model.

I have an array of integers which is shown in a list and input fields needs be generated on click of each item. All input fields should carry a generated value of ratio having base as 1. I also need to get the sum of numbers in the input field since the user can change the value.

With 3 items selected and divided ratio

With 4 items selected and divided ratio

My Code for this is

<div class="row" ng-repeat="kpi in SelectedKpiModel">
    <div class="small-2 columns" ng-click="View.RemoveSelectedKPI($index)" style="margin-top:0.5em;border:ridge;padding-bottom: 1em; padding-top:0.5em; text-align:center"><span class="fa fa-scissors"></span></div>
    <div class="small-4 columns" style="margin-top:0.5em;border:ridge;padding-bottom: 1em; padding-top:0.5em; text-align:center">
        {{kpi.id}}
    </div>
    <div class="small-4 columns" style="float:left;margin-top:0.5em;border:ridge; padding:0em">
        <input type="number" value="{{1/SelectedKpiModel.length}}" />
    </div>
</div>

How do I get the count of all the field values if user changes or how do I store the value of each field and retrieve if need ?

I tried like ng-model="{{1/SelectedKpiModel.length}}" but it gave me error.

Thanks.

| |
  • Can show us the error ? By the way if your length is 0 => en.wikipedia.org/wiki/Division_by_zero – Steeve Pitis Oct 7 '16 at 13:45
  • What does your controller look like? And ng-model is a two way binding, you can't use it for expressions like the above. If you need something like this, you must bind it to a getter/setter. – Veluria Oct 7 '16 at 13:46
  • I do not have any error. I want to get the sum of all the fields. It can have 3 fields or 5 fields depend upon the selection. Can you help me to sum the value of all the input field values. – Joseph Oct 7 '16 at 13:47
  • I am basically using the code given in jsfiddle.net/michaeldeongreen/22et6sao/9 . My controller has this logic and with this my html generated text inputs. – Joseph Oct 7 '16 at 13:51
  • Write a method in the controller that iterates the fields, adds the values and returns the sum. Then use it in your template eg: {{getSum()}} – Mihai Răducanu Oct 7 '16 at 14:21
0

You can use something like this -

<input type="number" ng-model="getLength()" />

and your function -

$scope.getLength = () => {
    return 1 / $scope.SelectedKpiModel;
}
| |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.