AngularJS ng-controller Directive

Last Updated : 3 Aug, 2022

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:

 
    Contents... 

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

<html>

<head>
    <title>ng-controller Directivetitle>
    <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">GeeksforGeeksh1>
    <h2>ng-controller Directiveh2>
    <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

<html>

<head>
    <title>ng-controller Directivetitle>
    <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 Directiveh2>
    <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:

 
Comment

Explore