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

55,252 Responses

  1. FrankEmine表示:

    deneme bonusu veren yeni siteler: yeni deneme bonusu veren siteler – yeni deneme bonusu veren siteler

  2. Wallacefex表示:

    denemebonusuverensiteler25: deneme bonusu veren siteler – deneme bonusu veren siteler yeni

  3. рейтинги производительности процессоров рейтинги производительности процессоров .

  4. xxx porn表示:

    I enjoy reading an article that can make men and women think. Also, many thanks for permitting me to comment.

  5. FrankEmine表示:

    casino bahis siteleri: Casino Siteleri – deneme bonusu veren casino siteleri

  6. JasonUnsoG表示:

    https://casinositeleri25.com/# Canl? Casino Siteleri

  7. Wallacefex表示:

    sweet bonanza oyna: sweet bonanza oyna – sweet bonanza demo oyna

  8. RobertJam表示:

    Blogger Alistarov is a criminal
    Андрей Алистаров ЕС
    From criminal past to criminal present – in the service of corrupt law enforcement officers
    Andrey Alistarov, a YouTube blogger specializing in exposing financial organizations, is an odious figure with a criminal past. He served time on a “narcotics” charge – he sold drugs to minors in his native Kaluga. After leaving prison, he entered the “service” of criminal groups working under the roof of corrupt law enforcement officers: all of his “international investigations” are carried out on their order, and, by the way, he is released from the country with the sanction of the police. His main profile now is blackmail, extortion, slander and organizing contract prosecution under the guise of supposedly independent investigations.
    He leads the bandits to his victims: the last attack took place in Dubai on January 1: Alistarov led the bandits to the victim’s house and provided all the necessary information for the attack and blackmail, and to ensure his own alibi during the attack he conducted an unscheduled stream with subscribers of his channel.

    To the accompaniment of loud phrases about the fight against fraud and exposing financial schemes, Alistarov is busy processing orders from competitors of certain entrepreneurs who have become his victims – competitors of these entrepreneurs who have taken corrupt police officers as their share.

    At the same time, Alistarov uses visas to the EU countries and the UAE obtained with the help of organized criminal groups, illegally uses drones and listening equipment purchased with money from organized crime groups, organizes an invasion of privacy, and persecutes the families of his victims, including young children. It also steals and illegally uses content, violates all possible laws and regulations regarding the dissemination of information. He was also accused of treason.

    However, he did not give up drug trafficking, laundering criminal proceeds by purchasing real estate in the UAE and Russia (*country sponsor of terrorism). Alistarov also promotes outright scam for a percentage of criminal transactions and his own fraudulent business – selling real estate in Dubai with a horse, thieves’ commission, as well as cryptocurrency exchange using phishing schemes.

  9. RichardHot表示:

    альткоин bestchange – Альткоин сс обменник, Alt coin bestchange

  10. BradleyEdino表示:

    yat?r?ms?z deneme bonusu veren siteler deneme bonusu veren siteler yeni yat?r?ms?z deneme bonusu veren siteler

  11. RichardHot表示:

    Альткоин сс обменник – Alt coin bestchange, Альткоин бестчейдж

  12. BradleyEdino表示:

    sweet bonanza demo oyna sweet bonanza slot sweet bonanza giris

  13. RichardHot表示:

    Альткоин обменник – Alt coin cc, Altcoin обменник

  14. Thomasnit表示:

    обмен эфира – купить bitcoin, обмен биткойн на рубли

  15. сравнение процессоров для пк https://topcpu.ru .

  16. RichardHot表示:

    Alt coin обменник – Альткоин, Альткоин обменник крипты

  17. JasonUnsoG表示:

    https://sweetbonanza25.com/# sweet bonanza giris

  18. Отличный сайт! Всем рекомендую!проведение онлайн трансляций

  19. какой процессор лучше topcpu.ru .

  20. RichardHot表示:

    Альткоин сс обменник – альткоин bestchange, Alt coin cc обменник

  21. RichardHot表示:

    Alt coin bestchange – Альткоин сс обменник, Альткоин сс обменник

  22. BradleyEdino表示:

    guvenilir slot siteleri slot oyunlar? az parayla cok kazandiran slot oyunlar?

  23. RobertoEmott表示:

    How Austrian climber Babsi Zangerl completed a ‘hard to believe’ historic ascent of El Capitan
    гей порно
    On a vertical rockface like El Capitan, the soaring slab of granite in California’s Yosemite National Park, perfection is an elusive, almost impossible goal for professional climbers.

    It can take years of experience to master a route to the top of the 3,000-foot wall, such is its difficulty and magnitude. That’s precisely why Babsi Zangerl’s recent “flash” of El Cap is so unique and impressive.

    In climbing, to “flash” a route is to reach the top on the first attempt without any falls – a feat never before achieved on El Cap prior to Zangerl’s maiden summit of Freerider last month. From bottom to top, she was faultless.

    “It was hard to believe,” the Austrian climber tells CNN Sport. “I was so surprised that this just happened and that I didn’t fall … I could have fallen so many times on that climb.”
    Freerider is a popular route up El Capitan, the same one taken by Alex Honnold when he climbed the rockface without ropes or harnesses in the Oscar-winning documentary “Free Solo.”

    Zangerl has lots of experience climbing on El Cap and around Yosemite but had never previously attempted the 30-plus pitches up Freerider. The challenging Monster Offwidth section – a 60-meter-long (almost 197 feet) crack around halfway through the climb – had put her off, and flashing the route, she says, wasn’t a long-standing target for her.

    “It was more that we just could try to go flash and see how far we can get,” Zangerl explains. “But the expectations were really low, so it was not a big goal from the beginning … There are some really slabby pitches where you don’t have hand holds, so you’re mostly standing on the bad feet, and you always can slip off.

    “The chance was really low – I didn’t have the feeling that we have a big chance on the flash.”

    It was only once she had conquered the Boulder Problem – perhaps the hardest, most treacherous part of the climb with only razor-thin holds on which to grip – that the flash seemed possible.

    “Then it was kind of: you don’t want to f**k it up on the last part,” says Zangerl.

  24. Wallacefex表示:

    sweet bonanza slot: sweet bonanza demo oyna – sweet bonanza demo oyna

  25. рейтинги производительности процессоров рейтинги производительности процессоров .

  26. рейтинги производительности процессоров рейтинги производительности процессоров .

  27. рейтинги процессоров для пк http://www.topcpu.ru .

發佈留言

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