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 Last Name:
Full Name: {{firstName + " " + lastName}}
.
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
[Try it Β»](#)
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
Last Name:
Full Name: {{fullName()}}
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
Last Name:
Full Name: {{firstName + " " + lastName}}
- {{ x.name + ', ' + x.country }}
YouTip