Medera
Medera

Reputation: 418

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>

Upvotes: 3

Views: 148

Answers (2)

Sumit Deshpande
Sumit Deshpande

Reputation: 2155

Add watch on A_Number to achieve the same. JSFiddle for reference - https://jsfiddle.net/9a2xz61y/3/

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.square = 0;
  $scope.$watch('A_Number', function(newValue, oldValue) {
    {
      if (!isNaN(newValue)) {
        $scope.square = $scope.A_Number * $scope.A_Number;
      }
    }
  });
});

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

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;
};

Upvotes: 4

Related Questions