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,096 Responses

  1. AxxePaish表示:

    The parts of the food that are not digested begin to be formed into stools faeces in the caecum before passing through the large intestine.
    The sites offer information about the drug and price of can i drink on amoxicillin at decreased prices
    If a lot show up, then there are probably bacteria there as well.

  2. Wow, this was a really quality post. In theory I’d like to write like this too – taking time and actual effort to make a good post… but what can I say… I procrastinate alot and never appear to get something done.

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

  4. I?ve been exploring for a bit for any high quality articles or blog posts in this kind of house . Exploring in Yahoo I finally stumbled upon this site. Reading this info So i am happy to convey that I have a very just right uncanny feeling I came upon just what I needed. I such a lot definitely will make certain to don?t overlook this web site and provides it a glance regularly.

  5. JamesEMULK表示:

    Уcтановкa натяжныx пoтолков энный сложнoсти? PАБОTАEM ПO BCEЙ Невьянск, Новоуральск. Европейcкоe качeство.лучшиe мaтериaлы. БEЗ ЗАПАXA. Выeзд специалистa зaмерщика бecплатно!!

    ремонт натяжного потолка

  6. I don’t know if it’s just me or if perhaps everyone else encountering problems with your blog. It seems like some of the written text within your content are running off the screen. Can someone else please provide feedback and let me know if this is happening to them as well? This could be a problem with my internet browser because I’ve had this happen previously. Many thanks

  7. Flvugm表示:

    buy generic voveran over the counter – order isosorbide without prescription cheap nimodipine pill

  8. Josephfub表示:

    top 10 online pharmacy in india india pharmacy world pharmacy india

  9. StevenThura表示:

    pop in this area and learn more http://www.mmnt.org/cat/rp/nspddfgurestv534.ru

  10. Feel free to surf to my blog post: Daycare Near Me

  11. Wnngonert表示:

    Im on a pressure all the time, please help me..
    Life is meaningful again at bactrim dosing and prompt ED now! Exciting freebies awaits you.
    It is helpful to ask that the conference be recorded or bring a tape recorder with you.

  12. MauriceGueda表示:

    mexico drug stores pharmacies: mexico pharmacies prescription drugs – mexico drug stores pharmacies

  13. ArthurKib表示:

    https://mexicopharmacy.cheap/# medication from mexico pharmacy

  14. вызвать наркологическую помощь skoraya-narkologicheskaya-pomoshch12.ru .

  15. Your house is valueble for me. Thanks!? This web page can be a walk-via for the entire information you needed about this and didn know who to ask. Glimpse here, and also you l definitely discover it.

  16. My friend sent me here and I thought I’d say hi, great blog.

  17. MWD Дизайн человека https://design-human.ru Дизайн человека. 2/4 Дизайн человека.

  18. RobertMef表示:

    buy prescription drugs from india: top 10 online pharmacy in india – buy medicines online in india

  19. Aw, i thought this was an extremely good post. In concept I have to put in writing in this way moreover – taking time and actual effort to make a excellent article… but exactly what do I say… I procrastinate alot by no indicates find a way to go carried out.

  20. VPI Дизайн человека https://rasschitat-dizayn-cheloveka-onlayn.ru Дизайн человека. 1/4 Дизайн человека.

  21. Josephfub表示:

    mexican border pharmacies shipping to usa buying prescription drugs in mexico online mexican rx online

  22. I would like to add that when you do not already have got an insurance policy or else you do not belong to any group insurance, you could well reap the benefits of seeking the aid of a health insurance agent. Self-employed or people with medical conditions ordinarily seek the help of any health insurance agent. Thanks for your article.

  23. i like it jobs because it is a high paying job and you work in an air conditioned office**

  24. Отличный сайт! Всем рекомендую!slivkursov.net

  25. TimothyBow表示:

    Услуги адвоката
    лучшие адвокаты по гражданским делам в москве
    Ищете надежную юридическую помощь? Официальный рейтинг адвокатов и юристов поможет найти проверенных специалистов, основываясь на высоком профессионализме, богатом опыте и положительных отзывах клиентов. Мы предлагаем уникальную возможность выбрать адвоката или юриста, способного эффективно разрешить ваше дело, будь то вопрос наследственного права, семейные споры или уголовного дела. Наш рейтинг поможет вам найти идеального кандидата, готового защитить ваши интересы в любой юридической ситуации и оказать юридические услуги профессионально и качественно

  26. I’m impressed, I have to admit. Really rarely do you encounter a weblog that’s both educative and entertaining, and let me tell you, you’ve got hit the nail for the head. Your notion is outstanding; the problem is a thing that not enough consumers are speaking intelligently about. We are happy we found this within my seek out some thing about it.

  27. LouisAlubs表示:

    At the end of the day, don’t we all want to be happy? Here are 5 ways to get there
    адвокат по семейным делам москва отзывы
    Americans are really into pursuing happiness.

    What happiness means is different for each individual and may shift over a lifetime: joy, love, purpose, money, health, freedom, gratitude, friendship, romance, fulfilling work? All of the above? Something else entirely? Many have even suggested that while we may think we know what will make us happy, we are often wrong.

    One man may have cracked the code for what makes a happy and healthier life — and he has the data to back him up.

    Dr. Robert Waldinger is the director of the Harvard Study of Adult Development — possibly the longest-running longitudinal study on human happiness, which started back in 1938. (The original study followed two groups of males, Harvard College students and adolescents in Boston’s inner city. It was expanded in recent decades to include women and people of more diverse backgrounds.)

    Plenty of components are at play in the quest for a happier life, but the key comes down to one main factor: quality relationships.

    “What we found was that the important thing was to stay actively connected to at least a few people, because we all need a sense of connection to somebody as we go through life,” Waldinger told CNN Chief Medical Correspondent Dr. Sanjay Gupta recently on his podcast Chasing Life.

    “And the people who were connected to other people lived longer and stayed physically healthier than the people who were more isolated,” he said. “That was the surprise in our study: not that people were happier but that they lived longer.”

  28. Hi there! Just wanted to drop by and say how I appreciate your blog. Your advice on affiliate marketing is right on target. Earning an income from home is a dream for many, and making money online makes it achievable. By leveraging your online presence and promoting items you have faith in, you can create a steady stream of income. It’s all about finding the perfect market and audience. Your blog serves as a treasured resource for anybody looking to dive into the world of affiliate marketing. Keep up the great work!

  29. MauriceGueda表示:

    online pharmacy college: irmat pharmacy – zyprexa pharmacy

發佈留言

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