Wednesday, May 30, 2018

AngularJS Controller

A Controller is defined by a JavaScript constructor function in AngularJS. AngularJS controllers control the data of AngularJS applications.  The ng-controller directive defines the application controller.

AngularJS Controller Example

<div ng-app="App" ng-controller="Ctrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('App'[]);
app.controller('Ctrl'function($scope) {
    $scope.firstName "Angular";
    $scope.lastName = "Js";
});
</script>
The ng-controller="Ctrl" attribute is an AngularJS directive. It defines a controller.
The "Ctrl" function is a JavaScript function and AngularJs will invoke the Ctrl function with $scope.  In AngularJS, $scope is the application object which can access all controller functions and variables. 

Here the controller creates two variables, firstName and lastNameBoth the varialbes are bound with ng-model directive which is a two way binding. When the user types the first name in the input field, it will be updated in firstName variable.

A controller can have methods which are variables as functions. These functions can be invoked from HTML and inside the controllers.

AngularJS Controller functions Example

<div ng-app="App" ng-controller="Ctrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('App', []);
app.controller('Ctrl', function($scope) {
    $scope.firstName = "Angular";
    $scope.lastName = "JS";
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    };
});
</script>
Here fullName is a controller function which is bound using expression binding. This function has the access to the controller variables and returns the full name. 


Click here to read about Custom directives.

Click here to read about Data binding.

2 comments:

  1. Can you post an article with sample project ?

    ReplyDelete

  2. This post will be very useful to us....i like your blog and helpful to me..
    Hire Angularjs Developer in India

    ReplyDelete

Whats new in Angular 8

Angular 8 was released in May 2019 and  th e key features of angular 8 are as follows in brief, Differential loading Dynamic imports ...