AngularJS - 控制器



AngularJS 應用主要依賴控制器來控制應用程式中的資料流。控制器使用 `ng-controller` 指令定義。控制器是一個包含屬性/特性和函式的 JavaScript 物件。每個控制器都接受 `$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` 定義為一個以 `$scope` 作為引數的 JavaScript 物件。

  • `$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` 檔案並檢視結果。

廣告