Controller AngularJS

Controller AngularJS控制 AngularJS 應用程序的数据

AngularJS 控制器是常規的 JavaScript 对象

Controller AngularJS

AngularJS 應用程序由控制器控制。

ng-controller 指令定義應用程序控制器。

控制器是由標準的 JavaScript 對象構造器創建的 JavaScript 对象

Mô hình AngularJS

<div ng-app="myApp" ng-controller="myCtrl">  
Tên: <input type="text" ng-model="firstName"><br>  
Họ: <input type="text" ng-model="lastName"><br>  
<br>  
全名: {{firstName + " " + lastName}}  
</div>  
<script>  
var app = angular.module('myApp', []);  
app.controller('myCtrl', function($scope) {  
  $scope.firstName = "Bill";  
  $scope.lastName = "Gates";  
});  
</script>

Thử ngay

應用程序說明:

AngularJS 應用程序由 ng-app="myApp" 定義。應用程序在 <div> 內運行。

ng-controller="myCtrl" Một thuộc tính là chỉ thị AngularJS. Nó định nghĩa một điều khiển.

myCtrl Một hàm là hàm JavaScript.

AngularJS sẽ sử dụng $scope gọi đối tượng điều khiển.

Trong AngularJS, $scope là đối tượng ứng dụng (chủ sở hữu của các biến và hàm ứng dụng).

Điều khiển trong phạm vi (firstNamelastName)và tạo hai thuộc tính (biến).

ng-model Cú pháp sẽ gán trường nhập vào thuộc tính điều khiển (firstName và lastName).

Các phương thức điều khiển

Ví dụ trên đã minh họa một đối tượng điều khiển có hai thuộc tính: lastName và firstName.

Các điều khiển có thể có các phương thức (như các biến của hàm):

Mô hình AngularJS

<div ng-app="myApp" ng-controller="personCtrl">  
Tên: <input type="text" ng-model="firstName"><br>  
Họ: <input type="text" ng-model="lastName"><br>  
<br>  
Họ và tên: {{fullName()}}  
</div>  
<script>  
var app = angular.module('myApp', []);  
app.controller('personCtrl', function($scope) {  
  $scope.firstName = "Bill";  
  $scope.lastName = "Gates";  
  $scope.fullName = function() {  
    return $scope.firstName + " " + $scope.lastName;  
  };  
});  
</script>

Thử ngay

Các điều khiển trong tệp exterior file

Trong các ứng dụng lớn, việc lưu trữ các điều khiển trong các tệp exterior file rất phổ biến.

Chỉ cần sao chép mã giữa thẻ <script> vào một tệp có tên personController.js trong tệp exterior file của nó:

Mô hình AngularJS

<div ng-app="myApp" ng-controller="personCtrl">  
Tên: <input type="text" ng-model="firstName"><br>  
Họ: <input type="text" ng-model="lastName"><br>  
<br>  
Họ và tên: {{fullName()}}  
</div>  
<script src="personController.js"></script>

Thử ngay

Một ví dụ khác

Đối với ví dụ tiếp theo, chúng ta sẽ tạo một tệp điều khiển mới:

angular.module('myApp', []).controller('namesCtrl', function($scope) {
  $scope.names = [
    {name:'Jani',country:'Norway'},
    {name:'Hege',country:'Sweden'},
    {name:'Kai',country:'Denmark'}
  ];
});

Lưu tệp thành namesController.js:

Sau đó sử dụng tệp điều khiển trong ứng dụng:

Mô hình AngularJS

<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>
</div>
<script src="namesController.js"></script>

Thử ngay