AngularJS 控制器


AngularJS 应用程序主要依靠控制器来控制应用程序中的数据流。控制器定义为 ng-控制器 指示。控制器是包含属性/属性和函数的 JavaScript 对象。每个控制器都接受 $scope 作为参数,它指的是控制器需要处理的应用程序/模块。

<div ng-app = "" ng-controller = "studentController">
    ...
</div>

在这里,我们声明一个名为 学生控制器 ,使用 ng-controller 指令。我们定义如下:

<script>
    function studentController($scope) {
        $scope.student = {
            firstName: "Mahesh",
            lastName: "Parashar",
         
            fullName: function() {
                var studentObject;
                studentObject = $scope.student;
                return studentObject.firstName + " " + studentObject.lastName;
            }
        };
    }
</script>
  • studentController 被定义为一个以 $scope 作为参数的 JavaScript 对象。

  • $scope 是指使用 studentController 对象的应用程序。

  • $scope.student 是 studentController 对象的一个​​属性。

  • firstName 和 lastName 是 $scope.student 对象的两个属性。我们将默认值传递给它们。

  • 属性 fullName 是 $scope.student 对象的函数,它返回组合名称。

  • 在 fullName 函数中,我们获取学生对象,然后返回组合名称。

  • 需要注意的是,我们还可以在单​​独的 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。

  • 现在,每当你在名字和姓氏输入框中输入任何内容时,你都可以看到全名自动更新。

例子


下面的例子展示了控制器的使用:

测试AngularJS.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>

输出


打开文件 测试AngularJS.htm 在网络浏览器中查看结果。