AngularJS 控制器
AngularJS 应用程序主要依靠控制器来控制应用程序中的数据流。使用 ng-controller 指令来定义控制器。控制器是一个包含属性/变量和函数的 JavaScript 对象。每个控制器将 scope 作为参数接受,scope 引用了控制器需要处理的应用程序/模块。
<div ng-app = "" ng-controller = "studentController">
   ...
</div>
在这里,我们使用ng-controller指令来声明一个名为studentController的控制器。我们将其定义如下 –
<script>
   function studentController(scope) {scope.student = {
         firstName: "Mahesh",
         lastName: "Parashar",
         fullName: function() {
            var studentObject;
            studentObject = $scope.student;
            return studentObject.firstName + " " + studentObject.lastName;
         }
      };
   }
</script>
- studentController被定义为一个JavaScript对象,其中$scope作为参数。
- 
$scope指的是使用studentController对象的应用程序。 
- 
$scope.student是studentController对象的一个属性。 
- 
firstName和lastName是$scope.student对象的两个属性。我们将默认值传递给它们。 
- 
属性fullName是$scope.student对象的一个函数,它返回组合后的名称。 
- 
在fullName函数中,我们获取student对象,然后返回组合后的名称。 
- 
请注意,我们还可以在单独的JS文件中定义控制器对象,然后在HTML页面中引用该文件。 
现在我们可以使用ng-model或表达式来使用studentController的student属性,如下所示:
Enter first name: <input type = "text" ng-model = "student.firstName"><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
- 我们将student.firstName和student.lastname绑定到两个输入框。
- 
我们将student.fullName()绑定到HTML。 
- 
现在,无论您在名字和姓氏输入框中输入任何内容,都可以自动更新全名。 
示例
以下示例显示了控制器的使用方式-
testAngularJS.htm
<html>
   <head>
      <title>Angular JS Controller</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/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>
输出
在Web浏览器中打开文件testAngularJS.htm并查看结果。

 极客教程
极客教程