สิ่งที่ควรรู้
UI Router Concept
UI Router จะมองเว็บเพจแต่ละหน้าเป็น state ภายใน State Machine เมื่อมีการเปลี่ยนหน้าก็จะเป็นการเปลี่ยนแปลงไปยัง state ที่กำหนดไว้
Basic Routing
$stateProvider เป็นฟังก์ชั่นที่ใช้สำหรับการกำหนด state ต่างๆใน single-page application
โดยจะทำการเรียกใช้ในฟังก์ชั่น config() ซึ่งโครงสร้างของ $stateProvider จะประกอบไปด้วย
- stateName : ชื่อของ state
- url : url ของ state ที่ระบุไว้
- template : ใช้ระบุส่วนเนื้อหาของ state นั้น (หรือใช้ templateUrl ใช้ในกรณีที่ include ไฟล์ html มา)
ซึ่งมีรายละเอียดดังนี้
1 2 3 4 5 6 7 8 | angular.module( 'application' , [ 'ui.router' ]) .config( function ($stateProvider, $urlRouterProvider) { $stateProvider .state( 'stateName' , { url: 'url' , template: '<p>this is part of stateName</p>' //or templateUrl: 'someFile.html' }); }); |
โดยการเรียกใช้ template ของ state นั้นจะไปแสดงใน directive ui-view
1 | < div ui-view></ div > |
1 2 3 | < div ui-view> < p >this is part of stateName</ p > </ div > |
หลักจากที่เราทำการกำหนด state ไว้แล้ว การที่เราจะเปลี่ยนข้ามไปในแต่ละ state นั้นมีได้ 3 วิธี ได้แก่
- เรียกใช้ฟังก์ชั่น $state.go() - ใน javascript เพื่อเปลี่ยน state
- คลิก link ที่มี ui-sref - กำหนด <a> ใน ui-sref ใส่ state ที่ระบุไว้ลงไป
- เลือกไปยัง URL ที่เกียวข้องกับ state นั้น - โดย url เริ่มต้นจาก #/ ตามด้วย url ที่ระบุไว้
โดยในเบื้องต้นเราจะใช้ ui-sref
ui-sref คือ อะไร
ในการที่จะทำการเปลี่ยนไปแต่ละ state ของ <a> จะใช้ ui-sref แทน href โดยมีลักษณะดังนี้
1 | < a ui-sref = "stateName" ></ a > |
ตัวอย่างการใช้งาน UI Router
ในไฟล์ js ทำการกำหนด state ขึ้นมา 2 state คือ home และ about
1 2 3 4 5 6 7 8 9 10 11 12 | angular.module( 'application' , [ 'ui.router' ]) .config( function ($stateProvider, $urlRouterProvider) { $stateProvider .state( 'home' , { url: '/home' , template: '<p>this is part of home</p>' }) .state( 'about' , { url: '/about' , template: '<p>this is part of about</p>' }); }); |
ในไฟล์ html ทำการสร้างเมนูลิงค์ไปยัง state ต่างๆ โดย <a> จะต้องกำหนด ui-sref เป็นชื่อ state ที่ระบุไว้ และใส่ ui-view ลงไป
1 2 3 4 5 6 7 8 9 10 | < div class = "container" > < ul class = "nav nav-pills" > < li >< a ui-sref = "home" >Home</ a ></ li > < li >< a ui-sref = "about" >about</ a ></ li > </ ul > < div > < p >Next of this line is ui-view</ p > < div ui-view></ div > </ div > </ div > |
สามารถดูตัวอย่างผลลัพธ์ได้ที่นี่ Demo
สังเกตได้ว่า เมื่อมีการคลิกที่ link จะทำให้ state เนื้อหาในส่วน ui-view จะเปลี่ยนไปตาม template ของ state
เพิ่ม Controller ลงใน state
ในกรณีที่ในแต่ละหน้ามีตัวแปรและฟังก์ชั่นต่างๆอยู่ภายในเราก็สามารถกำหนด property controller ใน state ได้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | angular.module( 'application' , [ 'ui.router' ]) .config( function ($stateProvider, $urlRouterProvider) { $stateProvider .state( 'home' , { url: '/home' , template: '<p>this is part of home</p>' }) .state( 'about' , { url: '/about' , template: '<p>Creator is {{name}}</p>' , controller: function ($scope) { $scope.name = "Google!!" ; } }); }); |