Jose the hose Jose the hose - 1 year ago 103
AngularJS Question

Update a span in a ng-repeat using ng-keyup

In a repeater and I display some records with some data, input field and a span tag in each row. When the user enters numeric value into the input field,
I want to do a calculation on it and display the result in the

tag. This will happen on keypress using

I’ve tried this but its not working, probably becuse I'm not using the model correctly...

<div ng-repeat="bet in $ctrl.bets">
<input class="form-control input-sm" ng-model="$index" type="text" ng-keyup="$ctrl.getReturn($index)">
<span>Return: </span><span id="$index" ng-model="$index"></span>

And in my controller I have this

vm.getReturn = function(index){
document.querySelector('#' + index ).html(value / 2);

I know its way off, but can someone tell me how to do this? Ta.

Answer Source

1st thing you can use ng-model only with input, select & special bootstrap components, Not span element. You could use ng-bind do bind value one way.

Other thing is don't play with $index which is added & managed by ng-repeat directive itself. I'd say rather add new property inside bet(each element of bets).


<div ng-repeat="bet in $ctrl.bets">
  <input class="form-control input-sm" ng-model="bet.myValue" type="text" ng-keyup="$ctrl.getReturn(bet.myValue)">
  <span>Return: </span><span id="$index" ng-bind="vm.getReturn(bet.myValue)"></span>

Accordingly manage calculation in getReturn function.

vm.getReturn = function(val) {
   return (val > 0 ? (val / 2): 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download