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...

50,814 Responses

  1. Darrelherse表示:

    en yeni slot siteleri: en iyi slot siteleri 2024 – en iyi slot siteler

  2. I’m extremely pleased to find this page. I wanted to thank you for your time for this fantastic read!! I definitely enjoyed every little bit of it and i also have you book marked to look at new information in your site.

  3. Отличный сайт! Всем рекомендую!проститутки Питера

  4. bobres-iptv表示:

    Right here is the perfect blog for anybody who really wants to find out about this topic. You understand a whole lot its almost hard to argue with you (not that I really will need to…HaHa). You certainly put a new spin on a topic that has been written about for a long time. Wonderful stuff, just excellent.

  5. AnrhHesia表示:

    One illustration of this is in the area of IHD.
    Best deals in town. Learn how to order neurontin for nerve pain in feet now!
    Placebo studies are inherently historical, anthropological, psychological, and sociological, as well as scientific and clinical.

  6. AgfnvHesia表示:

    This medication can cause unusual results with certain medical tests.
    Face off with ED problems and treatment. Contact clindamycin vs keflex at great prices
    Clinical Pharmacology and Therapeutics.

  7. AngdPaish表示:

    This diagnostics is for non-specific generalized overall stiffness that one cannot specifically pin point a focal area for the stiffness.
    Do your bit for the environment by checking the cephalexin for staph offered by a specialist low-cost pharmacy site
    The same logic holds for many of the viruses that cause common cold syndrome.

  8. Antonethuth表示:

    End of an era: The big change coming to European travel in November
    работа после вебкам

    In travel news this week: an accidental megadeal on first-class tickets, the world’s best-connected airport and why now is a good time to plan a trip to Europe. Plus a bit of relief for those of you traveling this Labor Day weekend.

    Goodbye to EU passport stamps
    Paper mementoes of our travels, from boarding cards to even passports themselves, are fast moving into obsolescence.

    The inky, smudgy joy of a fresh passport stamp will be a thing of the past for visitors to the 29 countries of the European Union Schengen Area starting November 10. That’s when the new automated Entry/Exit System (EES) comes into effect.

    It’s separate from the delayed ETIAS visa waiver program, which is due to start in the first half of 2025 and will mean travelers from outside the EU will be charged a €7 entry fee that is valid for three years.

    Destination inspiration
    Get your stamps while you can with these European vacation picks.

    Il dolce far niente – “the sweetness of doing nothing” – has been perfected by Italians on their vacations in southern sweet spots such as Naples, Ischia, Puglia, the Amalfi Coast and Capri. These remarkable photographs by UK photographer Lucy Laucht show how to relax the Italian way.

    In Hungary, the Gresham Palace is the grandest Budapest hotel of them all, having sat in its prime position overlooking the River Danube for more than a century. Here’s how this architectural gem looks in its current incarnation.

    Finally, if you’re considering a longer stay, an idyllic Swedish town is selling off land with prices so low you might think they’re mistakes. But Gotene, 320 kilometers (200 miles) southwest of Stockholm, is indeed selling plots with prices starting at just 1 krona, or 9 US cents, per square meter (11 square feet).

    Aviation news
    An airline accidentally offered a megadeal on first-class tickets, with 300 lucky customers getting savings of 85% off. Here’s what happened next.

    The staff at Australian flag carrier Qantas must have been flat-out like a lizard drinking sorting that mess out. And if you don’t understand that lingo, it’s time to check out our guide to Aussie slang.

    An airport on the edge of southeast Europe has been named the best connected in the world, with more than 300 direct flights to unique destinations. It’s been networking fast, too; it only opened in 2018.

  9. bobres-iptv表示:

    This website was… how do I say it? Relevant!! Finally I’ve found something which helped me. Thanks.

  10. JasonHes表示:

    This city is developing the world’s tallest timber tower, again
    работа для девушек сочи
    The US city of Milwaukee is already home to the world’s tallest timber tower. But another, even taller, wooden skyscraper could be added to its skyline, designed by Vancouver-based studio Michael Green Architects (MGA).

    The firm recently released plans for the development, which includes a 55-story tower made principally from mass timber — thick, compressed, multilayered panels of solid wood. If built, it would usurp the current world title holder, the 25-story Ascent tower by Korb + Associates Architects, as well as becoming the tallest building in the state of Wisconsin.

    MGA, which specializes in wooden architecture, hopes that the project will set a “new global benchmark for mass timber construction.”

    The project is part of the redevelopment of the Marcus Performing Arts Center, which opened in 1969 and won the Honor Award for Excellence in Architectural Design from the American Institute of Architects in 1970. Led by Neutral, which bills itself as a “regenerative development company,” the redesign will transform what is currently the center’s concrete parking lot into a space with residential units, offices, restaurants, cafes, grocery stores and public plazas. According to MGA, construction will cost an estimated $700 million. The plan is currently going through the city’s approval process, during which it is expected to evolve.

    Why timber?
    While the use of mass timber is steadily increasing worldwide, thanks to changes in building regulations and shifting attitudes towards the material, it has yet to match the sheer height of buildings made of concrete and steel — although a slew of timber high-rises have been proposed in recent years. MGA says its tower design would be approximately 600 feet (182 meters) tall — more than double the 284 feet (87 meter) tall Ascent tower.

    “The race for height is important,” said Michael Green, an architect and founder of MGA. “It’s not about showing off, it’s about showing what’s possible to the public.”

    He argued that the reason timber skyscrapers haven’t yet become mainstream is because climate change hasn’t been at the center of the conversation. “We didn’t really need to challenge the status quo of steel and concrete,” he said. “But because those materials are so hard on the climate, we had to find a different way to build towers and big buildings in general.”

  11. tonic greens表示:

    Hello There. I discovered your weblog the use of msn. That is an extremely neatly written article. I’ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly return.

  12. Wnenonert表示:

    Some women may experience fatigue and exhaustion.
    Major pharmacies compete on prices for nolvadex dosage on cycle pills, save by buying online
    It occurs most frequently in highly populated areas, often in cities.

  13. PokerTube表示:

    Here is my web site … PokerTube

  14. Sutkzq表示:

    order diclofenac sale – buy aspirin 75 mg for sale order generic aspirin

  15. Feel free to surf to my blog … Daycares By Category

  16. Отличный сайт! Всем рекомендую!проститутки СПб

  17. Printyhu9nep表示:

    Convert BTC to PayPal with ease and enjoy quick access to your funds.

發佈留言

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