Open In App

AngularJS ng-controller Directive

Last Updated : 03 Aug, 2022
Suggest changes
Share
Like Article
Like
Report

The ng-controller Directive in AngularJS is used to add a 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 actions. 

Syntax:

<element ng-controller="expression"> Contents... </element>

Parameter value:

  • expression: It refers to the name of the controller.

Example 1: This example uses the ng-controller Directive to display the input elements. 

HTML
<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">  </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 the ng-controller Directive to display content after clicking the button. 

HTML
<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">  </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:

 

Next Article

Similar Reads