Skip to content
Related Articles

Related Articles

Improve Article
AngularJS | ng-controller Directive
  • Last Updated : 28 Mar, 2019

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:
ngcontroller

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:
ngclick
After clicking Button 2:
ngclick




My Personal Notes arrow_drop_up
Recommended Articles
Page :