Dev Choudhary
Dev Choudhary

Reputation: 105

Controller not working in Angular JS

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.

Upvotes: 1

Views: 83

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

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>

Upvotes: 3

Chet
Chet

Reputation: 3729

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()}}.

Upvotes: 2

Related Questions