Jose the hose Jose the hose - 1 month ago 5
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

span
tag. This will happen on keypress using
ng-keyup


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


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

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

Markup

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

Accordingly manage calculation in getReturn function.

vm.getReturn = function(val) {
   return (val > 0 ? (val / 2): 0);
}  
Comments