扫码一下
查看教程更方便
AngularJS 应用程序主要依靠控制器来控制应用程序中的数据流。AngularJS 控制器是常规的 JavaScript 对象。控制器是使用ng-controller
指令定义的。每个控制器都接受 $scope
作为参数,该参数指的是控制器需要处理的应用程序/模块。
<div ng-app = "" ng-controller = "studentController">
...
</div>
在上面,我们使用 ng-controller 指令声明了一个名为studentController
的控制器。我们将其定义如下
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
注意
,我们还可以在单独的 JS 文件中定义控制器对象,并在 HTML 页面中引用该文件。 如,我们在 personController.js 中新建了控制器<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: {{firstName + " " + lastName}} </div> <script src="personController.js"></script>
以下示例显示了控制器的完整的使用
<html>
<head>
<title>Angular JS 控制器</title>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
Enter first name: <input type = "text" ng-model = "student.firstName"><br>
<br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
</body>
</html>