Home > Web Front-end > JS Tutorial > AngularJS Basic Study Notes Controller_AngularJS

AngularJS Basic Study Notes Controller_AngularJS

WBOY
Release: 2016-05-16 15:59:53
Original
1062 people have browsed it

AngularJS controller is used to control the data of AngularJS applications.

AngularJS controllers are ordinary JavaScript objects.

AngularJS Controller
AngularJS applications are controlled through controllers.

The ng-controller directive defines an application controller.

A controller is a JavaScript object that can be created through standard JavaScript object constructors.

<div ng-app="myApp" ng-controller="myCtrl">

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('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
});
</script>

Copy after login

Code explanation:

AngularJS application is defined by ng-app="myApp". The effective scope of the application is in the

where ng-app is located.

 ng-controller="myCtrl" attribute is an AngularJS directive, which defines a controller.

The myCtrl function is an ordinary JavaScript function.

AngularJS uses the $scope object to call controllers.

In AngularJS, $scope is an application object (that is, the owner of application variables and functions).

The controller contains two properties (or variables): firstName and lastName. They are attached to the $scope object.

The ng-model directive binds the value of the input tag to the controller's properties (firstName and lastName).

Controller methods
The above example shows that the controller object contains two properties: lastName and firstName.

Controllers can also contain methods (assign functions to variables):

<div ng-app="myApp" ng-controller="personCtrl">

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('myApp', []);
app.controller('personCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
  $scope.fullName = function() {
    return $scope.firstName + " " + $scope.lastName;
  }
});
</script>

Copy after login

Put the controller in an external file
In large applications, controller code is often written in external files.

Copy the code in the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template