Search code examples
angularjsdata-bindingangularjs-scopeangularjs-bindings

Angularjs not updating variables


I want to display/update the calculation answer directly without the need of aditional buttons. Or do i need a function and button to apply the changes?

<div ng-app="myApp" ng-controller="myCtrl">

A_Number: <input type="number" step="1" ng-model="A_Number"><br> 

Display (A_Number): {{A_Number}}
<br>
square: {{square}} 
</div>

controller:

<script> 
var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope) {

$scope.square = $scope.A_Number * $scope.A_Number; 
}); 
</script>

Solution

  • Make square as a method & use that method in interpolation directive, so that will evaluate on each digest.

    Markup

    square: {{square()}} 
    

    Code

    $scope.square = function(){
        //made error free
        if(!isNaN($scope.A_Number))
          return $scope.A_Number * $scope.A_Number;
        return 0;
    };