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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:
ngcontroller

Example 2: This example uses ng-controller Directive to display content after clicking the button.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:
Before click:
ngclick
After clicking Button 2:
ngclick



My Personal Notes arrow_drop_up


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.