Home >Web Front-end >JS Tutorial >How to use AngularJS controller? Angularjs controller controls angularjs application instance resolution
This article mainly introduces the use of angularjs controllers. angularjs controllerControl the data of angularjs application. Now let’s take a look at this article
Introduction to angularjs controller:
AngularJS controllerControl Data of AngularJS application .
AngularJS controllers are regular JavaScript objects.
AngularJS applications are controlled by controllers. The
ng-controller directive defines the application controller.
Controllers are JavaScript objects created by the standard JavaScript object constructor.
<p ng-app="myApp" ng-controller="myCtrl"> 名: <input type="text" ng-model="firstName"><br> 名: <input type="text" ng-model="lastName"><br> <br> 姓名: {{firstName + " " + lastName}} </p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); </script>
Application resolution:
AngularJS applications are defined by ng-app. The application runs within
.
ng-controller="myCtrl" attribute is an AngularJS directive. is used to define a controller.
myCtrl function is a JavaScript function.
AngularJS uses $scope objects to call controllers.
In AngularJS, $scope is an application object (belonging to application variables and functions).
The controller's $scope (equivalent to scope, control scope) is used to save the object of the AngularJS Model (model).
The controller creates two properties in the scope (firstName and lastName).
ng-model The directive binds the input fields to the controller's properties (firstName and lastName). (If you want to see more, go to the PHP Chinese website AngularJS Development Manual column to learn)
The above example demonstrates a method with lastName and firstName. Controller object with two properties.
Controllers can also have methods (variables and functions):
<p ng-app="myApp" ng-controller="personCtrl"> 名: <input type="text" ng-model="firstName"><br> 姓: <input type="text" ng-model="lastName"><br> <br> 姓名: {{fullName()}} </p> <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>
In large applications, the controller is usually stored in an external file.
Just copy the code in the