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

53,081 Responses

  1. And with most origin films, this one spent considerable time in establishing the ground rules for discovery of powers, the relationships between characters, all primed for action sequences in between long drawn narratives building up toward that inevitable big bang conclusion which contained everything but the kitchen sink.

  2. Drstobeese表示:

    med rx online pharmacy: buy pharmacy – online pharmacy reviews generic viagra

  3. Online Casino表示:

    Aw, this was an exceptionally nice post. Finding the time and actual effort to make a top notch article… but what can I say… I put things off a whole lot and don’t seem to get anything done.

  4. ATD Дизайн человека https://rasschitat-dizayn-cheloveka-onlayn.ru Дизайн человека. 6/3 Дизайн человека.

  5. DavidLog表示:

    изготовление автономеров https://gos-dublikaty150.ru/

  6. xsgcy124表示:

    .

  7. Отличный сайт! Всем рекомендую!печать на холсте в Тюмени

  8. Easydrorbix表示:

    amoxicillin mexican pharmacy: discount drug store pharmacy – no prescription pharmacy paypal

  9. GregoryEvell表示:

    В магазине напольных покрытий представлены различные виды напольных покрытий и выберите тот, который соответствует вашим потребностям. Например, ламинат подходит для помещений с высокой проходимостью, кварцвиниловая плитка полностью водостойкая, подходит для любых в том числе и влажный помещений, а ковровое покрытие создаст уютную атмосферу в спальне. https://ламинат1.рф/

  10. JeffreyPlaiz表示:

    https://easydrugrx.com/# Ventolin inhalator
    compare prescription prices

  11. EJC Дизайн человека https://rasschitat-dizayn-cheloveka-onlayn.ru Дизайн человека. 2/5 Дизайн человека.

  12. I got what you intend, thanks for putting up. Woh I am glad to find this website through google.

  13. hey there and thank you for your information – I’ve certainly picked up anything new from right here. I did however expertise some technical points using this site, as I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my email and could look out for much more of your respective intriguing content. Ensure that you update this again soon..

  14. Drstobeese表示:

    zofran online pharmacy: online pharmacy tylenol 3 – ambien cr online pharmacy

  15. Your blog never ceases to amaze me, it is very well written and organized.–;*;

  16. MatthewSouse表示:

    Паркетная доска – это паркет из натурального дерева, который используется для отделки пола. Он покрыт износоустойчивым лаком или масло-воском с различными видами обработки (браш, волна, фаска), что делает его популярным выбором для создания уютной атмосферы в доме. Паркетная доска может быть различных видов, от классического дуба до экзотических пород дерева. Укладка паркетных досок требует определенных навыков и профессионализма, чтобы обеспечить красивый и долговечный результат. https://kvarcvinil3.ru/

  17. Chuckt表示:

    What’s up, future millionaires? Charles here, your captain on this journey to the treasure island of affiliate marketing. Ever imagined making $1,000 a day without breaking a sweat? Well, pinch yourself, due to the fact that you’re not dreaming! Grab your eye patch and your sense of experience, and let’s cruise the high seas of chance. All aboard the revenue ship!

  18. Great site! I recommend it to everyone!realistic dildos

  19. After research a number of of the blog posts in your website now, and I really like your manner of blogging. I bookmarked it to my bookmark web site record and can be checking back soon. Pls take a look at my site as well and let me know what you think.

  20. JeffreyPlaiz表示:

    https://easydrugrx.com/# wholesale pharmacy
    online pharmacy doxycycline

  21. my sister ordered sofa beds on the internet, they are quite nice and very comfy to sit in~

  22. I would like to thank you for the efforts you have put in penning this site. I’m hoping to see the same high-grade blog posts by you in the future as well. In truth, your creative writing abilities has motivated me to get my own, personal website now 😉

  23. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.

  24. WWO Создание карты расстановки сил в коллективе. https://rasstanovkiural.ru

  25. phieuguige表示:

    Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. phieuguige-grab-bat-net

  26. Chuckt表示:

    What’s up, future millionaires? Charles here, your captain on this journey to the treasure island of affiliate marketing. Ever imagined making $1,000 a day without breaking a sweat? Well, pinch yourself, due to the fact that you’re not dreaming! Grab your eye patch and your sense of adventure, and let’s sail the high seas of opportunity. All aboard the revenue ship!

  27. TimothySaw表示:

    Ламинат – это популярное покрытие для пола, которое сочетает в себе прочность, долговечность и стильный внешний вид. Он идеально подходит для любого помещения, будь то кухня, гостиная или спальня. Ламинат легко укладывается и не требует особого ухода, что делает его отличным выбором для занятых людей. Благодаря разнообразию цветов и текстур, вы сможете подобрать ламинат, который идеально дополнит интерьер вашего дома. Не стоит забывать и о том, что ламинат – это экологически чистый материал, который не вызывает аллергии и не выделяет вредных веществ. Приобретая напольные покрытия в нашем магазине вы обновите свой дом с помощью качественного ламината! https://kvarcvinil1.ru/

發佈留言

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