3

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>

2 Answers 2

4

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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

@Medera glad to hear that.. Thanks :)
0

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

2 Comments

Yes agree - when object is complex and more fields to watch. I just mentioned as different approach to achieve the result.
still it shouldn't, also you should not use true option at the end of watcher, as here its no meaning for it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.