iT邦幫忙

DAY 2
4

已廢除請轉移至(用MAN架構打造超人般的網頁應用程式:復仇者聯盟)系列 第 2

用MAN架構打造超人般的網頁應用程式-Day 08:AngularJS - Plugin:UI-Router

在昨天介紹的Routing中,讓大家對換頁有基本的概念後就要來介紹這個AngularJS上必裝超強的plugin:UI-Router。
用MAN架構打造超人般的網頁應用程式系列文章
用MAN架構打造超人般的網頁應用程式系列文章

UI-Router

github

UI-Router是AngularJS的一個routing framework,主要是幫助你可以有架構將你的頁面分開成不同的子頁面呈現Nested view,不同於原本的$route service,UI-Router 是一個透過state的架構來切換頁面,這讓你有更大的彈性來切換你的頁面。

使用方式如下:

	<!doctype html>
	<html ng-app="myApp">
	
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script src="js/angular-ui-router.min.js"></script>
    ...
	
	
    	...
    <script>
        var myApp = angular.module('myApp', ['ui.router']);
    </script>
	
	

範例

範例

首先在結構上總共有五個頁面,頁面上大致說明如下

  • index.html

範例首頁,載入所有css,js與設定ng-app的應用範圍,重點設定如下:

	myApp.config(function($stateProvider, $urlRouterProvider) {
  	//
  	// For any unmatched url, redirect to /state1
  	$urlRouterProvider.otherwise("/state1");
  	//
  	// Now set up the states
  	$stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: "partials/state1.html"
    })
    .state('state1.list', {
      url: "/list",
      templateUrl: "partials/1.list.html",
      controller: function($scope) {
        $scope.items = ["A", "List", "Of", "Items"];
      }
    })
    .state('state2', {
      url: "/state2",
      templateUrl: "partials/state2.html"
    })
    .state('state2.list', {
      url: "/list",
        templateUrl: "partials/state2.list.html",
        controller: function($scope) {
          $scope.things = ["A", "Set", "Of", "Things"];
        }
      })
    });

這邊透過設定每個state對應的url中的templateUrl與controller來分配連接版面與各版面操控的內容。

  • route1.html

當url指到#/route1時顯示的頁面,裡面包含一個子狀態的設定顯示route1.list.html的內容,url指到#/route2時顯示的頁面,裡面包含一個子狀態的設定顯示route2.list.html的內容,原始碼如下:

	<!-- partials/state1.html -->
	<h1>Route 1</h1>
	<hr/>
	<a ui-sref=".list">Show List</a>
	<div ui-view></div>




	<!-- partials/state2.html -->
	<h1>Route 2</h1>
	<hr/>
	<a ui-sref=".list">Show List</a>
	<div ui-view></div>

這邊透過ui-sref的方式指定Show List的內容來自於各自檔名接上.list之後的html頁面內容。

  • route1.list.html與route2.list.html

     <!-- partials/state1.list.html -->
     <h3>List of State 1 Items</h3>
     <ul>
     <li ng-repeat="item in items">{{ item }}</li>
     </ul>
    
    
    
    
     <!-- partials/state2.list.html -->
     h3>List of State 2 Things</h3>
     <ul>
     <li ng-repeat="thing in things">{{ thing }}</li>
     </ul>
    

這邊透過ngRepeat的方式分別讀出item與thing內的物件

結語

介紹到這邊,基本上大家已經可以建立一個簡單地SPA網頁,接下來就要再一一介紹AngularJS各項強大的火力給大家認識了!Day-8 over!


上一篇
用MAN架構打造超人般的網頁應用程式-Day 07:AngularJS - Routing
下一篇
用MAN架構打造超人般的網頁應用程式-Day 09:AngularJS - Directives
系列文
已廢除請轉移至(用MAN架構打造超人般的網頁應用程式:復仇者聯盟)4
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0

我要留言

立即登入留言