oto260 oto260 - 3 months ago 9
AngularJS Question

AngularJS two-way binding. Returning user inserted input

User inserts value in the HTML:

</div>`<div ng-app="xpCalc" ng-controller="Xp Calculator">

<p>Insert your current Level <input type="number" ng-model="currentLevel"></p>

<h2>{{$scope.currentXp}}</h2>

</div>`


And my js script calculates and returns the results:

var app=angular.module('xpCalc', []);
app.controller('Xp Calculator', function($scope){
$scope.currentLevel;
$scope.currentXp=function(){
var output=0;
for (var thisLVL =1; thisLVL >= $scope.currentLevel; thisLVL++) {
return output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
}}});


But somehow I don't see the results in the view. What can be wrong?

Answer

Use

<div ng-app="xpCalc" ng-controller="xpCalculatorController">

<p>Insert your current Level  <input type="number" ng-model="currentLevel"></p>

<h2>{{currentXp()}}</h2>

</div>

and

var app=angular.module('xpCalc', []);
app.controller('xpCalculatorController', function($scope){
$scope.currentLevel = 1;
$scope.currentXp=function(){
    var output=0;
    for (var thisLVL =1; thisLVL <= $scope.currentLevel; thisLVL++) {
        output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
    }
    return output;
  }
});

Note: your loop operator >= was inverted and infinite, changed to <=. Also, you cannot name your controller Xp Calculator with a space...

See https://plnkr.co/edit/BMomweYVGLlTsv2tTjfS?p=preview