I am new to Angular JS. To see the working of controller, I implemented this simple code where two numbers are taken as an input from the users and their sum is calculated in the controller and the result is displayed in the view. But somehow it does not work. The code is as follows :

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>

<body>
<div ng-app="CalculatorApp" ng-controller="CalculatorController">
<p> Number 1 <input type="number" ng-model="a"></p>
<p> Number 2 <input type="number" ng-model="b"></p>
<p> Addition is {{c}} </p>
</div>

angular.module('CalculatorApp', [])
.controller('CalculatorController', function($scope) 
{
$scope.c=$scope.a + $scope.b;
});

</body>
</html>

Please guide.

share|improve this question
    
Yoiu forgot your script tags... – naneri Dec 6 '15 at 12:58

You need to add JavaScript code in script tag with type='text/javascript', so that while parsing the page desired JavaScript run.

And for getting the calculated result on HTML you should follow @chet answer.

Code

<script type="text/javascript">
    angular.module('CalculatorApp', [])
    .controller('CalculatorController', function($scope) {
         $scope.c = $scope.a + $scope.b; //should follow @chet answer
    });
</script>
share|improve this answer

First off, you forgot to wrap your JavaScript in <script></script> tags. Even then you have a problem.

Change Addition is {{c}} to Addition is {{a + b}}, and drop the controller calculation altogether.

The code in the function defines the controller, it is not executed every time something changes.

Alternately, you could define a function on $scope, and then call the function.

$scope.calc = function() {
    return $scope.a + $scope.b;
};

Then change your HTML to Addition is {{calc()}}.

share|improve this answer
    
I missed the addition part +1 for that.. – Pankaj Parkar Dec 6 '15 at 13:06
    
Got the script tags part. – Dev Choudhary Dec 6 '15 at 14:16
    
Got the script tags part. Also know that the addition can be performed without the controller in the view. But just wanted to understand the working of the controller. Is the function necessary to do the addition in the controller. – Dev Choudhary Dec 6 '15 at 14:24
    
Yes, you would have to define a function. – Chet Dec 6 '15 at 14:36
    
Any reasons for necessity of function in the controller. Can you elaborate ? Sorry for this as I am totally new to angular js – Dev Choudhary Dec 6 '15 at 17:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.