Mortz Mortz - 11 days ago 6
AngularJS Question

Why does angular js not automatically update twice of the number?

I am an absolute newbie at angularjs and I am trying to write a code where the html should automatically display twice the number I enter -

This is what my code looks like -

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link href="./style.css" rel="stylesheet"/>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
</head>

<body>
<div ng-controller="frmCtrl">
<label>Name:</label>
<input type="text" ng-model="number" placeholder="Enter a name here">
<hr>
<h1>Hello {{twice}}!</h1>
</div>

<script>
app = angular.module("myApp", []);
app.controller("frmCtrl", function($scope) {
$scope.number = "2";
$scope.twice = 2*$scope.number;}
);
</script>
</body>
</html>


However, this code does not work at all - when I update the value in the input box, the twice is not updated automatically, although, initially it shows a value of 4 corresponding to twice of 2.

Why is this happening? And is there a better/correct way to achieve what I am trying to achieve here?

Thanks for your help

Answer

Better way would be, you could modify twice value on change of number value. For the same you could write ng-change function of number input field and modify twice value from change function.

<input type="text" ng-model="number" placeholder="Enter a name here" ng-change="updateTwice()"/>
<h1>Hello {{twice}}!</h1>

Code

$scope.updateTwice = function(){
   $scope.twice = 2 * $scope.number;
}

Another way could be change twice as function. Call twice on view binding so that will get evaluate on each digest cycle, making sure that whatever displayed on the view is 2 times of number ng-model.

<h1>Hello {{twice()}}!</h1>

Code

$scope.twice = function(){
 return 2*$scope.number;
}

Comments