oto260 oto260 - 5 months ago 24
AngularJS Question

AngularJS, the variables doesn't change in the view

I've created this simple calculation where the user inserts his levels and by that we get the combat calculation. But the problem is, the view never change, because the variables are somehow static.
Please find jsfiddle for code.

Code link :


There are a few issues with your code.

First using a model for each input element does not tell angular that you wish to capture the change events, in other words that you wish angular get notified when these element value has been changed. That's why you need to use the ng-change directive, which role is to bind the new values to the DOM element.

The second issue is that angular does not know when the model values have been changed, until you do not tell to watch them.

Taking into account the above consideration this is how the refactored code should look like:

var app= angular.module("cmbtCalc", []);

app.controller('CombatCalculatorController', function($scope){
    $scope.result = 0;
    $scope.ALvl = 1 ;
    $scope.SLvl = 1 ;
    $scope.MLvl = 1 ;
    $scope.RLvl = 1 ;
    $scope.HLvl = 10 ;
    $scope.DLvl = 1 ;
    $scope.PLvl = 1 ;

    function RangeMage (real){
        return 0.325 * (Math.floor( real/ 2)+real); 


    ['SLvl', 'ALvl', 'MLvl', 'RLvl', 'HLvl', 'DLvl', 'PLvl'].forEach(function(val) {
        $scope.$watch(val, function(newValue, oldValue) {
            $scope.melee = 0.325 * ($scope.ALvl + $scope.SLvl);
            $scope.base = 0.25 * ( $scope.DLvl + $scope.HLvl + Math.floor ($scope.PLvl / 2 ));

    $scope.calculatecmbt = function (){   
        $scope.result = Math.max($scope.melee, $scope.RealRange, $scope.RealMage) + $scope.base;  
        return $scope.result;   


And inside your html you have to define a model for a ng-change directive:

<h2 ng-model="RealRang" ng-change="calculatecmbt">
{{calculatecmbt() | number}}

And here is the working code: https://jsfiddle.net/tvbjscp9/5/