AngularJS – Tab 介紹篇

為了方便文章閱讀,本篇將Tab翻譯成頁籤

這個案例的複雜度會比較前面高一些,因為它不僅僅是使用我們一直提到的AngularJS,為了要製作頁面上面的一些互動效果,還加入了Bootstrape這個通常被用來當RWD的框架,不過也僅僅是套用了幾個類別,所以大家也不用太擔心,接下來我們先看一下這個案例最後希望要達成的效果頁面

在看過了目標頁面後,我們先來了解一下需要怎麼樣架構我們的HTML,首先是CSS和Javascript的引入,分別是AngularJS、jQuery、Bootstrap CSS以及Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

在HTML文件中,必須有項目清單標籤ul、li,而在ul標籤中需套用nav nav-pills這兩個css類別,這兩個類別是由Bootstrape的css所提供的,li標籤是包覆著超連結的a標籤,下圖案例是希望可以產生三個頁籤。

AngularJS Part5 Slide1
AngularJS Part5 Slide1

在a標籤中加入ng-click=”tab = 1″、ng-click=”tab = 2″、ng-click=”tab = 3″去設定當使用者按下連結後tab變數會隨著變化,另外為了方便觀察是否成功,在頁面上利用表達式將tab變數顯示出來。

AngularJS Part5 Slide1
AngularJS Part5 Slide2

若一切順利,在我們按下不同的頁籤連結時,畫面上應該會有數字上面的變化。

AngularJS Part5 Slide3
AngularJS Part5 Slide3
AngularJS Part5 Slide4
AngularJS Part5 Slide4

接下來開始製作點選頁籤後的內容頁面,同樣的內容頁面也應該有三個才對,在HTML中產生三個div,其中套用Bootstrape所提供的CSS panel類別,div的內容部分可依照需求置入。

AngularJS Part5 Slide5
AngularJS Part5 Slide5

在div中利用ng-show去判斷tab變數的值來切換顯示。

AngularJS Part5 Slide6
AngularJS Part5 Slide6

完成後,在我們點選不同的連結時,內容的部分也應該會隨著變動。

AngularJS Part5 Slide7
AngularJS Part5 Slide7

接下來我們在section標籤中設定ng-init=”tab=1″的屬性來決定tab變數的初始值。

AngularJS Part5 Slide8
AngularJS Part5 Slide8

接下來在li內新增ng-class的屬性,依tab變數的值來切換active的CSS屬性(該屬性由Bootstrape提供樣式),其中三個連續的等號是判斷該變數與值完全相同的意思。

AngularJS Part5 Slide9
AngularJS Part5 Slide9

這個動作的目的是希望當網友點選之後,可以如下圖所示,清楚的標示目前頁面上所顯示的是第幾個項目。

AngularJS Part5 Slide10
AngularJS Part5 Slide10

到目前為止,大概就完成了我們希望呈現的頁籤效果,大家可以透過JS Bin來測試看看到目前為止的程式碼。

<!DOCTYPE html>
<html ng-app>
<head>
<meta name="description" content="AngularJS Tabs Example 1">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <meta charset="utf-8">
  <title>AngularJS Tabs Example 1</title>
</head>
<body>
  <section ng-init="tab=1">
    
    <ul class="nav nav-pills">
      <li ng-class="{ active: tab===1 }">
        <a href="" ng-click="tab=1">滑鼠墊</a>
      </li>
      <li ng-class="{ active: tab===2 }">
        <a href="" ng-click="tab=2">馬克杯</a>
      </li>
      <li ng-class="{ active: tab===3 }">
        <a href="" ng-click="tab=3">杯墊</a>
      </li>
    </ul>
    
    <div class="panel" ng-show="tab===1">
      <h4>馬老師雲端研究室 滑鼠墊</h4>
      <p>產品介紹...</p>
    </div>
    <div class="panel" ng-show="tab===2">
      <h4>馬老師雲端研究室 馬克杯</h4>
      <p>產品介紹...</p>
    </div>
    <div class="panel" ng-show="tab===3">
      <h4>馬老師雲端研究室 杯墊</h4>
      <p>產品介紹...</p>
    </div>
  
  </section>
</body>
</html>

在看完了上面的案例之後,我們可以觀察到程式邏輯判斷的部分都是直接撰寫在HTML頁面上,那如果我們要把邏輯判斷的部分從HTML拆開寫到Javascript檔又應該要如何處理呢?首先,不用說的當然是必須要有應用程式的建立以及控制器囉!下圖中我們開始新增控制器,並且在section標籤中,輸入ng-controller=”panelController as panel”的屬性,相信在看了前幾篇教學的同學們對於這樣的項目是再熟悉不過了!接下來在控制器中,決定tab變數的初始值,就可以把原來的ng-init屬性刪除了。

AngularJS Part5 Slide11
AngularJS Part5 Slide11

在ng-click後去執行控制器中的selectTab函數,並且針對該函數帶入不同的值,利用帶入的值來改變tab變數值。

AngularJS Part5 Slide12
AngularJS Part5 Slide12

在ng-click後去執行控制器中的isSelected函數,也帶出不同的值給函數,讓函數可以回傳tab===1或2、3這樣的內容給ng-show使用。

AngularJS Part5 Slide13
AngularJS Part5 Slide13

這樣一來我們邏輯判斷的部分就會和網頁內容有所區隔,大家也可以透過JS Bin來測試這樣的程式結構。

<!DOCTYPE html>
<html ng-app="store">
<head>
<meta name="description" content="AngularJS Tabs Example 2">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <meta charset="utf-8">
  <title>AngularJS Tabs Example 2</title>
</head>
<body>
  <section ng-controller="PanelController as panel">
    <ul class="nav nav-pills">
      <li ng-class="{ active: panel.isSelected(1) }">
        <a href="" ng-click="panel.selectTab(1)">滑鼠墊</a>
      </li>
      <li ng-class="{ active: panel.isSelected(2) }">
        <a href="" ng-click="panel.selectTab(2)">馬克杯</a>
      </li>
      <li ng-class="{ active: panel.isSelected(3) }">
        <a href="" ng-click="panel.selectTab(3)">杯墊</a>
      </li>
    </ul>
    <div class="panel" ng-show="panel.isSelected(1)">
      <h4>馬老師雲端研究室 滑鼠墊</h4>
      <p>產品介紹...</p>
    </div>
    <div class="panel" ng-show="panel.isSelected(2)">
      <h4>馬老師雲端研究室 馬克杯</h4>
      <p>產品介紹...</p>
    </div>
    <div class="panel" ng-show="panel.isSelected(3)">
      <h4>馬老師雲端研究室 杯墊</h4>
      <p>產品介紹...</p>
    </div>
  </section>
</body>
</html>
(function(){
  var app = angular.module('store', []);
  
  app.controller('PanelController', function(){
    this.tab = 1;
    
    this.selectTab = function(setTab){
      this.tab = setTab;
    };

    this.isSelected = function(checkTab){
      return this.tab === checkTab;
    };
  });
  
})();

You may also like...

61,819 Responses

  1. Elmerbuils表示:

    pin-up: pin up – pin-up

  2. MichaelJed表示:

    Curious about DeFi? Juice Finance is shaking up the space with its powerful Juice Finance DeFi platform. With smart Juice Finance lending, high Juice Finance APY, and seamless Juice Finance staking, users are maximizing returns with ease. Built for security and performance, the Juice Finance app offers features like Juice Finance cross-margin lending and Juice Finance on Blast L2. Wondering what is Juice Finance? Check the Juice Finance FAQ or read the Juice Finance Blog. Ready to earn more? Juice Finance mobile app is live—get started at https://juice.ac today!

  3. Victorsox表示:

    Ready to battle in style? Super Sushi Samurai is the action-packed Web3 game taking over the Blast Network! With strategic gameplay, NFT ownership, and real SSS token rewards, the Super Sushi Samurai game is more than just fun—it’s crypto-powered. Want to know how to play Super Sushi Samurai? It’s easy—just follow the Super Sushi Samurai guide and dive in. Curious about Super Sushi Samurai review? Players love the thrill and the earnings. Get started now at https://sssgame.ink and slice your way to victory!

  4. ZackaryGer表示:

    http://pinupaz.top/# pin up casino

  5. Elmerbuils表示:

    вавада официальный сайт: вавада казино – вавада казино

  6. BrianStani表示:

    вавада: vavada casino – vavada вход

  7. Jamestonse表示:

    Say hello to Ring Exchange—the DeFi platform made for next-gen crypto users. Whether you’re trading on the Ring Exchange aggregator, exploring Ring Protocol crypto, or earning with Ring Exchange staking, the experience is seamless. Ring Exchange launchpad opens new project access, while the RING token powers the ecosystem. Wondering how it compares? See why traders are switching in every Ring Exchange review. Start your journey now at https://ringexchange.org !

  8. VernonPap表示:

    Say hello to Marinade Finance—the smarter way to stake on Solana! With Marinade staking, your Marinade SOL turns into Marinade Staked SOL, unlocking liquidity through Marinade mSOL. The platform is powered by the community via Marinade DAO and the MNDE token. Wondering about Marinade vs Lido? Users trust Marinade for its strong APY and proven Marinade Finance Audits. Start staking now at https://marinade.ink and grow your Solana securely!

  9. Brianbleft表示:

    Say hello to ThorSwap—your ultimate multi-chain trading hub. From Thor Crypto Change to THORYield and ThorSwap Staking, every feature is designed to maximize your DeFi experience. The ThorSwap THOR Token powers governance and rewards, with real-time ThorSwap Token Price updates and full ThorSwap NFT Support. Need help? ThorSwap Documentation has you covered, and the ThorSwap Referral Program brings extra rewards. Start earning today at https://thorswap.cc !

  10. Ismaelendut表示:

    Sablier is built for builders, teams, and DAOs. With powerful Sablier token vesting, Sablier mirror integration, and Sablier crypto tools, itтАЩs the go-to for real-time finance. Backed by the trusted Sablier protocol and Sablier Labs, you can stream confidently on Sablier Ethereum. Need to claim? Use Sablier Claim or explore the Sablier app to manage it all. Visit https://sablier.cc and experience financial automation like never before!

  11. KODgcd表示:

    Онлайн-консультация психолога. Анонимный чат с психологом телеграм. Психолог t me.

    87123 проверенных отзывов.
    Анонимный прием.
    Поможет поставить цель терапии и приведет к результату.
    Записаться на консультацию.

  12. Освободитесь от рутины с автоматикой Somfy
    Автоматика Somfy Автоматика Somfy . прокарниз

  13. Mastersjq表示:

    Чат с психологом в телеге. Психолог онлайн анонимно. Анонимный чат с психологом телеграм.

    Эмоциональное состояние: тревога, депрессия, стресс, эмоциональное выгорание.
    Психолог, Сайт психологов.
    Индивидуальное консультирование.

  14. KennethKex表示:

    pin-up: pin-up – pin up casino

  15. KennethKex表示:

    pin up azerbaycan: pin-up – pin up az

  16. KennethKex表示:

    pin up az: pin up casino – pin up az

  17. JamesMaf表示:

    Instadapp is built for the future of finance! With smart Instadapp Fluid automation, deep integration with Instadapp MakerDAO, and full Instadapp Security/Audit transparency, it’s trusted by thousands. Whether you’re exploring Instadapp Pro, managing Instadapp Flashloan tools, or claiming your Instadapp Airdrop, everything is simple and secure. Want to understand Instadapp Governance or the INST Token? It’s all in the Instadapp overview. Ready to start? Visit http://instaoapp.com and join the next generation of DeFi now!

  18. Jamestonse表示:

    RingExchange is here to redefine crypto trading. With deep liquidity from the RingX Aggregator and a smooth Ring Exchange DEX interface, users enjoy top-tier execution across chains. Use the Ring Exchange tutorial to get started, and take full advantage of Ring Exchange crypto tools. From RING crypto to the trusted Ring Exchange BNB Chain support, it’s built to scale. Curious about ProtocolRing? It’s all part of the vision. Visit https://ringexchange.org and explore Ring Exchange DeFi today!

  19. Elmerbuils表示:

    вавада официальный сайт: вавада – vavada

  20. Elmerbuils表示:

    пин ап казино: пин ап казино – пин ап зеркало

  21. Richardfek表示:

    pin-up casino giris pinup az pin up azerbaycan

  22. Richardfek表示:

    pinup az pin up azerbaycan pin up

  23. BrianStani表示:

    вавада зеркало: вавада зеркало – vavada вход

  24. ZackaryGer表示:

    https://pinuprus.pro/# пин ап казино официальный сайт

  25. Ismaelendut表示:

    New to token streaming? Sablier is revolutionizing crypto payments with real-time, on-chain finance. From Sablier deposit to Sablier Claim and Sablier Receive, itтАЩs seamless and secure. Built on the trusted Sablier protocol, users stream funds with precision on Sablier Ethereum. Curious about Sablier review? Users love its simplicity, safety, and efficiency. Want to know how to use Sablier app? ItтАЩs easyтАФSablier sign up today at https://sablier.cc and experience next-gen money flows now!

  26. Elmerbuils表示:

    vavada: вавада казино – вавада

  27. Richardfek表示:

    вавада официальный сайт vavada вавада

  28. ZackaryGer表示:

    https://vavadavhod.tech/# вавада

  29. Victorsox表示:

    Super Sushi Samurai is redefining gaming on the Blast Network! With real ownership through Super Sushi Samurai NFT, thrilling battles, and community-driven gameplay, it’s the perfect blend of fun and finance. Track the SSS token price, use your SSS token wisely, and dominate the Super Sushi Samurai land. From Super Sushi Samurai tutorial to Super Sushi Samurai crypto rewards, it’s all here. Ready to play? Visit https://sssgame.ink and become a sushi legend today!

發佈回覆給「MichaelJed」的留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。