Thursday, August 14, 2014

การเรียกใช้ AngularJS ผ่าน Javascript อื่น

หลายคนคงเคยได้ยินชื่อ AngularJS มาบ้างนะครับ (ช่วงนี้เห็นคนพูดถึงกันเยอะ)   เป็น JavaScript Framework ตัวนึงที่ผมรู้สึกทึ่งกับความสามารถของมันมากเลย  อีกอย่างคือการเขียนหรือการใช้งานก็ง่ายด้วย  โดยตัว angularjs ใช้สถาปัตยกรรม MVC  ตัวผมเองก็เคยลองใช้มาเมื่อประมาณ 2 ปีที่แล้ว  ยังไม่มีโอกาสได้ใช้อีกเลย(ยังไม่ชำนาญเท่าไหร่ครับ :D )  เพราะว่างานส่วนใหญ่เจอกับ Javascript น้อยมาก  ถ้าใครเคยใช้คงจะมีปัญหานึงคือ  แล้วเราจะเรียกใช้ตัวแปรหรือฟังก์ชั่นที่อยู่ใน scope ของ angularjs ยังไงล่ะ  (ผมคิดว่าถ้าเราใช้ angularjs แบบเต็มรูปแบบอาจจะไม่ต้องเรียกใช้เลยนะ) แต่เผื่อใครต้องใช้ตัว angularjs ก็เตรียมมาไว้ให้ครับ

Environment ที่ใช้

  • Atom Editor (อันนี้มีคนแนะนำจาก Programmer Thai Blood ครับ แจ๋วดี )
  • AngularJS 1.2.22
  • JQuery-ui 1.11 (ผมเอามาเรียกใช้ตัว dialog ครับ)

hello.html

<!doctype html>
<html >
  <head>
    <link rel="stylesheet" type="text/css" href="jquery-ui/jquery-ui.min.css">
    <script src="jquery-ui/external/jquery/jquery.js"></script>
    <script src="jquery-ui/jquery-ui.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  </head>
  <body>
    <div id="my-app" ng-app>
      <button id="input-name" type="button" >Input Name</button>
      <hr/>
      <h1>Hello {{name}} !!</h1>
    </div>
    <div id="dlg-input">
      <label>Name:</label>
      <input id="text-name" type="text" />
    </div>
  </body>

  <script type="text/javascript" >
    $(function(){
      $("#dlg-input").dialog({
        autoOpen:false,
        resizable: false,
        height:200,
        modal: true,
        buttons: {
          "OK": function() {
            var scope = $("#my-app").scope();
            scope.$apply(function(){
              scope.name = $("#text-name").val();
            });
            $( this ).dialog( "close" );
          },
          "Cancel": function() {
            $( this ).dialog( "close" );
          }
        }
      });

      $("#input-name").button().on( "click", function() {
        $( "#dlg-input" ).dialog("open");
      });
    });
  </script>
</html>

ตัวอย่างนี้ผมเอามาจากเว็บ https://angularjs.org/ เลยแต่เอามาปรับนิดหน่อยเพื่อจะได้เห็นภาพการใช้งาน
จุดหลักของตัวอย่างคือโค๊ดจุดนี้ครับ

           var scope = $("#my-app").scope();
                scope.$apply(function(){
                scope.name = $("#text-name").val();
            });

เราสามารถเรียกใช้ฟังก์ชั่น scope() เพื่อเรียกตัว scope ของ angularjs มาใช้ได้โดยเราต้องเรียกผ่าน $apply เพื่อให้โค๊ดส่วนนั้นทำงาน

ข้อสังเกตคือเราสามารถเรียก scope() ได้ทุกตัวที่อยู่ใน element ที่เราใส่ ng-app เข้าไปครับ

Source Code : t002.zip




No comments:

Post a Comment