YouTip LogoYouTip

Angularjs Controllers

# AngularJS Controllers * * * AngularJS controllers **control** the data of AngularJS applications. AngularJS controllers are regular **JavaScript objects**. * * * ## AngularJS Controllers AngularJS applications are controlled by controllers. The **ng-controller** directive defines the application controller. Controllers are **JavaScript objects** created by standard JavaScript **object constructors**. ## AngularJS Example
First Name:
Last Name:

Full Name: {{firstName + " " + lastName}}
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); [Try it Β»](#) Application Explanation: The AngularJS application is defined by **ng-app**. The application runs inside the
. The **ng-controller="myCtrl"** attribute is an AngularJS directive. It is used to define a controller. The **myCtrl** function is a JavaScript function. AngularJS invokes the controller using the **$scope** object. In AngularJS, $scope is the application object (belonging to the application variables and functions). The controller's **$scope** (which is equivalent to scope, control range) is used to store the AngularJS Model object. The controller creates two properties (**firstName** and **lastName**) in the scope. The **ng-model** directive binds the input fields to the controller's properties (firstName and lastName). * * * ## Controller Methods The example above demonstrates a controller object with two properties: lastName and firstName. Controllers can also have methods (variables and functions): ## AngularJS Example
First Name:
Last Name:

Full Name: {{fullName()}}
var app = angular.module('myApp', []); app.controller('personCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; $scope.fullName = function() { return $scope.firstName + " " + $scope.lastName; } }); [Try it Β»](#) * * * ## Controllers in External Files In larger applications, it is common to store controllers in external files. Simply copy the code inside the tag into an external file named [personController.js](#): ## AngularJS Example
First Name:
Last Name:

Full Name: {{firstName + " " + lastName}}
[Try it Β»](#) * * * ## Other Examples The following example creates a new controller file: angular.module('myApp', []).controller('namesCtrl', function($scope){ $scope.names = [{name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'}]; }); Save the file as [namesController.js](#): Then, use the controller file in the application: ## AngularJS Example
  • {{ x.name + ', ' + x.country }}
[Try it Β»](#)
← Angularjs FiltersAngularjs Directives β†’