Runoob Tutorial ArchiveEnglish

AngularJS controller

AngularJS controller


AngularJS controllerControllerAngularJS application data.

AngularJS controller is a regularJavaScript object.


AngularJS Controller

AngularJS applications are controlled by controllers.

ng-controllerThe directive defines the application controller.

A controller isa JavaScript object, constructed by the standard JavaScriptobject constructorCreate.

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"myCtrl"

Name:

<

input

type=

"text"

ng-model=

"firstName"

<

br

Last name:

<

input

type=

"text"

ng-model=

"lastName"

<

br

<

br

Name:

{{firstName + " " + lastName}}

<

/div

<

script

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

    $scope.firstName = "John";

    $scope.lastName = "Doe";

});

<

/script

Try it »

Application parsing:

AngularJS applications are defined byng-appThe application runs in

.

ng-controller="myCtrl"attribute is an AngularJS directive. Used to define a controller.

myCtrlfunction is a JavaScript function.

AngularJS uses the **$scope** object to call the controller.

In AngularJS, $scope is an application object (belonging to application variables and functions).

The controller's$scope(equivalent to scope, control range) is used to store the AngularJS Model object.

The controller created two properties in the scope (firstNameandlastName).

ng-modelbinds the input field to the controller's properties (firstName and lastName).


Controller method

The example above demonstrates a controller object with the properties lastName and firstName.

Controllers can also have methods (variables and functions):

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"personCtrl"

Name:

<

input

type=

"text"

ng-model=

"firstName"

<

br

Last name:

<

input

type=

"text"

ng-model=

"lastName"

<

br

<

br

Name:

{{fullName()}}

<

/div

<

script

var app = angular.module('myApp', []);

app.controller('personCtrl', function($scope) {

    $scope.firstName = "John";

    $scope.lastName = "Doe";

    $scope.fullName = function() {

return $scope.firstName + " " + $scope.lastName;

}

});

<

/script

Try it »


Controller in an external file

In large applications, controllers are usually stored in external files.

Just need to