Using Functions in AngularJS Controller

So far we have covered the following directives in AngularJS:

If you are new to Controllers in AngularJS I would recommend you to go through this article. I hope you are clear with the basics of controllers now in AngularJS. Now let us see how we can use functions in Controllers.
Copy the below code in a HTML file.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
  4.   
  5. <body>  
  6.   
  7.     <div ng-app="myAngularApp" ng-controller="Ctrl">  
  8.   
  9.         City: <input type="text" ng-model="city"><br><br><br> Country: <input type="text" ng-model="country"><br><br><br> Result: {{output()}}  
  10.   
  11.     </div>  
  12.   
  13.     <script>  
  14.         var app = angular.module('myAngularApp', []);  
  15.         app.controller('Ctrl', function($scope)  
  16.         {  
  17.             $scope.city = "Mumbai";  
  18.             $scope.country = "India";  
  19.             $scope.output = function()  
  20.             {  
  21.                 return $scope.city + " " + $scope.country;  
  22.             }  
  23.         });  
  24.     </script>  
  25.   
  26. </body>  
  27.   
  28. </html>  
We have created a function in which we have concatenated the two variable using scope object. This function name is called to display the desired output.



Let us see the output of the program.

This is how we can use functions in controllers in AngularJS.