Mortz Mortz - 1 year ago 70
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">
<link href="./style.css" rel="stylesheet"/>
<script src=""></script>

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

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

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 Source

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>


$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>


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download