วันพฤหัสบดีที่ 8 มกราคม พ.ศ. 2558

AngularJS HTML Events

HTML Events คือ เหตุการณ์ต่างๆที่เกิดขึ้นกับ HTML Element เช่น การคลิก การโฟกัส การเปลี่ยนแปลงค่า เป็นต้น

ในบทความนี้จะอธิบายถึงการดักจับ "การคลิก" ปุ่มของผู้ใช้ โดยจะใช้ ng-click ใน <button>

ตัวอย่าง

<!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="myController">

    <p>{{ count }}<p>
    <p>
      <button ng-click="count = count + 1">+</button>
      <button ng-click="count = count - 1">-</button>
    </p>

    <p ng-show="mytext">Hellow World</p>
    <button ng-click="showText()">Show Text</button>


  </div>
<script>
function myController($scope) {
    $scope.count = 0;
    $scope.mytext=false; 

    $scope.showText=function(){
                        $scope.mytext = !$scope.mytext;
                    };   
}
</script> 

</body>
</html>

อธิบายขั้นตอนการทำงานได้ ดังนี้
  • กำหนด ng-app และ สร้าง Controller ชื่อ myController
  • กำหนดค่าเริ่มต้นให้ตัวแปร count มีค่าเท่ากับ 0 ตัวแปร mytext มีค่าเป็น false
  • เมื่อกดปุ่ม + จะทำการนำตัวแปร count มา +1 แล้วแสดงผล เช่นเดียวกัน ถ้ากดปุ่ม - จะนำ count มา -1
  • เมื่อกดปุ่ม Show Text จะกำหนดค่าให้กับ ืng-show โดยเรียกใช้ฟังก์ชั่น เพื่อแปลงค่า mytext เป็นค่าตรงกันข้าม ด้วยการกำหนดเครื่องหมาย ! หน้าตัวแปร mytext เช่น ถ้าเดิมเป็น false จะแปลงเป็น true

ไม่มีความคิดเห็น:

แสดงความคิดเห็น