สิ่งที่ควรรู้
$urlRouterProvider คือ อะไร ?
เป็นตัวจัดการกับ URL ทุกครั้งที่มีการเรียก URL ที่กำหนดไว้ โดยมีฟังก์ชั่นที่ให้ใช้งาน 3 ฟังก์ชั่น
- when()
- otherwise()
- rule()
when()
when() เป็นฟังก์ชั่นสำหรับเมื่อเราต้องการ redirect โดยมีรายละเอียดดังนี้
- what - เป็น pathOfUrl ที่ส่งมา
- handler - เป็น pathOfUrl ที่ต้องการ redirect ไป / ฟังก์ชั่น
1 2 3 | .config( function ($urlRouterProvider) { $urlRouterProvider.when(what, handler); }); |
กรณีที่ handler เป็นฟังก์ชั่นจะสามารถ return ค่าได้ 3 ลักษณะ
- False - เพื่อระบุให้ $urlRouter ไม่ตรงกับ ที่กำหนดไว้ โดย $urlRouter จะไปหา state ที่ถูกต้อง ใช้เพื่อระบุว่าผู้ใช้เข้าใช้ได้ถูก URL
- String (URL) - จะทำการ redirect ไปที่ URL ดังกล่าว
- True/Undefinded - เพื่อระบุให้ $urlRouter รู้ว่ากำลังใช้งาน URL ดังกล่าว
otherwise()
otherwise() เป็นฟังก์ชั่นที่ใช้ในกรณีที่ URL ไม่ถูกต้อง otherwise จะทำการ redirect ไปยัง url ที่เราต้องการ
1 2 3 4 5 6 7 8 | .config( function ($urlRouterProvider){ // otherwise use for invalid route $urlRouterProvider.otherwise( '/index' ); // Advance otherwise $urlRouterProvider.otherwise( function ($injector, $location){ ... some advanced code... }); |
rule()
rule() เป็นฟังก์ชั่นที่ใช้ในการกำหนด custom routing ก่อนที่จะไปเช็คกับ routing อื่นๆ ที่กำหนดไว้
1 2 3 4 | .config( function ($urlRouterProvider){ $urlRouterProvider.rule( function ($injector, $location) { return '/index' ; }); |
ตัวอย่างการใช้งาน otherwise
ทำการสร้าง state ไว้ 3 state
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | .config( function ($stateProvider, $urlRouterProvider) { $stateProvider .state( 'one' , { url: '/one' , template: '<p>this is state one</p><p ui-view></p>' }) .state( 'one.two' , { url: '/two' , template: '<p>this is state one-two</p>' }) .state( 'three' , { url: '/three' , template: '<p>this is state three</p>' }); }); |
กำหนด otherwise ให้เมื่อกรอก url ไม่ถูกต้องให้ส่งกลับมาที่ state one
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | .config( function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise( '/one' ); $stateProvider .state( 'one' , { url: '/one' , template: '<p>this is state one</p><p ui-view></p>' }) .state( 'one.two' , { url: '/two' , template: '<p>this is state one-two</p>' }) .state( 'three' , { url: '/three' , template: '<p>this is state three</p>' }); }); |
สามารถดูตัวอย่างผลลัพธ์ได้ที่นี่ Demo
สังเกตได้ว่า กรณีที่ URL ไม่ตรงกับ state ไหนเลย จะทำการ redirect ไปยัง state one