Introduction:

Here we will explain to what is controller  in AngularJS or how to use controller  in AngularJS or How to declare a Controller In AngularJS with ng-controller directive or How to create function , properties , attribute in AngularJS Controller with Example:


Description:

AngularJS controller to control the flow of data in the application. AngularJS controller is defined with ng-controller directive. AngularJS controller is a JavaScript object containing attributes/properties and functions. AngularJS controller accepts $scope as a parameter which refers to the application/module that controller is to control.

Now I am going to declared a controller MyController using ng-controller directive. See Below –

MyController

 

<script>

    var mainApp = angular.module("MyApp", []);

    mainApp.controller('MyController', function ($scope) {

        $scope.User = {

            Name: "Aditya Kumar Patel",

            Age: "24"    

};

    });

</script>

Above Code MyController defined as a JavaScript object with $scope as argument. $scope refers to application which is to use the MyController object. $scope.User is property of MyController object. Name and Age are two properties of $scope.User object. We've defined the default values Name=”Aditya Kumar Patel” and Age=”24”

Now I am going to use controller in our HTML page . show below-

Example

<script src="~/Scripts/jquery-3.1.1.js"></script>

<script src="~/Scripts/angular.js"></script>

<h2>AngularJS Application</h2>

<div ng-app="MyApp" ng-controller="MyController">

    Enter Name: <input type="text" ng-model="User.Name"><br><br>

    Enter Age: <input type="text" ng-model="User.Age"><br><br>

    Name : {{User.Name}}

    Age : {{User.Age}}

</div>

<script>

    var mainApp = angular.module("MyApp", []);

    mainApp.controller('MyController', function ($scope) {

        $scope.User = {

            Name: "Aditya Kumar Patel",

            Age: "24"       

};

});

</script>

Now we run application and see Output

Thanks.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like