AngularJS คอนโทรลเลอร์
- หน้าก่อนหน้า AngularJS การผูกข้อมูล
- หน้าต่อไป AngularJS สคริปต์
AngularJS คอนโทรลเลอร์ควบคุมข้อมูลของโปรแกรม AngularJS。
AngularJS controller คือ JavaScript object。
AngularJS คอนโทรลเลอร์
โปรแกรม AngularJS ถูกควบคุมโดย controller
ng-controller คำสั่งนิรุกต์ระบุ controller ของโปรแกรม
controller ถูกสร้างด้วย constructor ของ object JavaScript มาตรฐาน JavaScript object。
ตัวอย่าง AngularJS
<div ng-app="myApp" ng-controller="myCtrl"> ชื่อ: <input type="text" ng-model="firstName"><br> นามสกุล: <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>
คำอธิบายโปรแกรม:
โปรแกรม AngularJS มี ng-app="myApp"
definiก. โปรแกรมทำงานด้วย <div>。
ng-controller="myCtrl"
คุณภาพเป็นออกซ์ท์รูค์ของ AngularJS มันกำหนดคอนโทรลเลอร์
myCtrl
ฟังก์ชันเป็นฟังก์ชัน JavaScript
AngularJS จะใช้ $scope
เรียกใช้โอปเจ็คคอนโทรลเลอร์
ใน AngularJS $scope คือตัวแปรของโปรแกรม (เจ้าของตัวแปรและฟังก์ชันของโปรแกรม)
คอนโทรลเลอร์ในขอบเขต (firstName
และ lastName
)ที่สร้างสองคุณภาพ (ตัวแปร)
ng-model
ออกซ์ท์รูค์จะบอกเชื่อมโยงในช่องบอกข้อความกับคุณภาพของคอนโทรลเลอร์ (firstName และ lastName)
วิธีคอนโทรลเลอร์
ตัวอย่างด้านบนแสดงให้เห็นคอนโทรลเลอร์ที่มีนามสกุล และ ชื่อ สองคุณภาพ
คอนโทรลเลอร์ยังสามารถมีวิธี (เป็นตัวแปรของฟังก์ชัน):
ตัวอย่าง AngularJS
<div ng-app="myApp" ng-controller="personCtrl"> ชื่อ: <input type="text" ng-model="firstName"><br> นามสกุล: <input type="text" ng-model="lastName"><br> <br> ชื่อเต็ม: {{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>
คอนโทรลเลอร์ในไฟล์นอก
ในโปรแกรมที่ใหญ่มากขึ้น การเก็บคอนโทรลเลอร์ในไฟล์นอกเป็นไปตามที่มักจะทำ
แค่คัดโค้ดที่อยู่ระหว่างแท็ก <script> ไปใส่ในไฟล์ที่มีชื่อ personController.js ในไฟล์นอก:
ตัวอย่าง AngularJS
<div ng-app="myApp" ng-controller="personCtrl"> ชื่อ: <input type="text" ng-model="firstName"><br> นามสกุล: <input type="text" ng-model="lastName"><br> <br> ชื่อเต็ม: {{fullName()}} </div> <script src="personController.js"></script>
ตัวอย่างอื่น
สำหรับตัวอย่างต่อไปนี้ จะสร้างไฟล์คอนโทรลเลอร์ใหม่:
angular.module('myApp', []).controller('namesCtrl', function($scope) { $scope.names = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'} });
บันทึกไฟล์เป็น namesController.js:
หลังจากนั้นใช้ไฟล์คอนโทรลเลอร์ในโปรแกรม:
ตัวอย่าง 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>
- หน้าก่อนหน้า AngularJS การผูกข้อมูล
- หน้าต่อไป AngularJS สคริปต์