วันจันทร์ที่ 5 มกราคม พ.ศ. 2558

AngularJS Controllers

AngularJS Controller เป็นตัวควบคุม AngularJS Application โดยจะมีการสร้าง Function ที่มีชื่อเดียวกับ Controller เพื่อควบคุมการทำงานต่างๆ

ตัวอย่าง

<!DOCTYPE html>

<html ng-app="">

<head>
  <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
</head>

<body>
 <div ng-controller="control">
   Name: <input type="text" ng-model="name"><br>
   Address: <input type="text" ng-model="address"><br><br>

  My name is {{ name }} . I stay in {{ address}}

 </div>

<script>
function control($scope) {
    $scope.name= "Jame",
    $scope.address= "Bangkok"
}
</script>

</body>
</html>

อธิบายทีละส่วน


  • ประกาศขอบเขตที่ใช้ AngularJS ด้วยคำสั่ง ng-app ใน <html>
  • ประกาศ Controller ที่ชื่อ control ด้วยคำสั่ง ng-controller ใน <div> แสดงว่า ภายใน <div> ถูกควบคุมด้วย controller ที่ชื่อ control จะสังเกตุเห็นว่ามีการสร้าง function ที่มีชื่อเดียวกัน คือ control
  • ผูกค่าจาก <input> ด้วย ng-model
  • นำค่าที่ผูกไว้มาแสดง ด้วย {{ }} ซึ่งสามารถ แสดงผลร่วมกับข้อความธรรมดาได้ด้วย
  • ในส่วน function control มี $scope ทำหน้าที่เก็บข้อมูลเพื่อนำไปอ้างอิง ** ต้องใช้ $scope เท่านั้นนะ ห้ามตั้งชื่อเอง ** จากนั้นมีการอ้างอิง model ที่ชื่อ name และ address ซึ่ง Jame และ Bangkok เป็นค่า default ที่กำหนดให้กับ $scope

นอกจากนี้ ยังสามารถเรียกใช้ฟังก์ชั่นจากไฟล์ที่แยกต่างหากได้

ไฟล์ control.js

<script>
function control($scope) {
    $scope.name= "Jame",
    $scope.address= "Bangkok"
}
</script>

จากนั้นทำการแก้ไขส่วนของ <script> จากเดิมที่มีการสร้าง function ให้แก้เป็น

<script src="control.js"></script>


1 ความคิดเห็น: