AngularJS | ng-controller Directive
The ng-controller Directive in AngularJS is used to add controller to the application. It can be used to add methods, functions and variables that can be called on some event like click, etc to perform certain action.
Syntax:
<element ng-controller="expression"> Contents... </element>
Where expression refers to the name of the controller.
Example 1: This example uses ng-controller Directive to display the input elements.
<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-controller Directive</h2><br> <div ng-controller="geek"> Name: <input class="form-control" type="text" ng-model="name"> <br><br> You entered: <b><span>{{name}}</span></b> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.name = "geeksforgeeks"; }); </script> </body> </html> |
Output:

Example 2: This example uses ng-controller Directive to display content after clicking the button.
<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-click Directive</h2> <div ng-controller="app"> <button class="btn btn-default" ng-click="best()"> Button 1 </button> <button class="btn btn-primary" ng-click="notbest()"> Button 2 </button><br> <p>Quick sort is <b>{{res}}</b>.</p> </div> <script> var app = angular.module('app', []); app.controller('app', function ($scope) { $scope.best = function () { return $scope.res = "best"; }; $scope.notbest = function () { return $scope.res = "not always good"; }; }); </script> </body> </html> |
Output:
Before click:

After clicking Button 2:

Recommended Posts:
- AngularJS | ng-app Directive
- AngularJS | ng-if Directive
- AngularJS | ng-value Directive
- AngularJS | ng-cut Directive
- AngularJS | ng-src Directive
- AngularJS | ng-csp Directive
- AngularJS | Directive
- AngularJS | ng-jq Directive
- AngularJS | ng-selected Directive
- AngularJS | ng-readonly Directive
- AngularJS | ng-required Directive
- AngularJS | ng-paste Directive
- AngularJS | ng-srcset Directive
- AngularJS | ng-change Directive
- AngularJS | ng-blur Directive
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



