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

  1. 33win表示:

    There’s definately a great deal to learn about this issue. I really like all of the points you have made.

  2. Robertengep表示:

    http://easyrxindia.com/# indian pharmacies safe

  3. An intriguing discussion is definitely worth comment. I do believe that you ought to write more on this subject matter, it may not be a taboo matter but generally people do not speak about these topics. To the next! Best wishes.

  4. Feel free to visit my web blog – Daycare Near Me

  5. Peterhew表示:

    cheapest online pharmacy india: best india pharmacy – buy prescription drugs from india

  6. porn表示:

    That is a great tip particularly to those new to the blogosphere. Short but very precise information… Thanks for sharing this one. A must read post.

  7. Mazrgzt表示:

    Привет!
    Официальное получение диплома техникума с упрощенным обучением в Москве
    maps.google.bt/url?sa=t&url=aurus-diploms.com

  8. I really like it when people get together and share opinions. Great site, stick with it!

  9. Stephenideox表示:

    Offenheit fur Finanzinnovationen zu einer Drehscheibe fur bahnbrechende Geschaftsideen entwickelt. Wir sind bestrebt, die traditionellen Unternehmensgrenzen zu erweitern und unseren Kunden auf der ganzen Welt neue Start-up-Moglichkeiten zu bieten. Unser Ziel ist es, einen Mehrwert fur internationale Unternehmen zu schaffen, indem wir die grenzenlosen Moglichkeiten der Europaischen Union wahrend ihres technologischen Aufstiegs nutzen und nahtlose Geschaftsentscheidungen nur einen Klick entfernt ermoglichen.

    Effektivitat unserer Arbeit von den kollektiven Bemuhungen jedes einzelnen Teammitglieds abhangt. Unsere Vision basiert auf gegenseitiger Unterstutzung und taglicher Zusammenarbeit, angetrieben durch das Engagement mit Kunden, Partnern und Kollegen. Wir integrieren die Unternehmenswerte in jeden Aspekt unserer Arbeit und betonen, wie wichtig es ist, realistische Ziele zu setzen, die Verantwortung fur Entscheidungen im Team zu ubernehmen und Projekte bis zum Abschluss zu begleiten.

  10. Stephenideox表示:

    Cost of starting and maintaining a company. If you are planning to start a micro-business with a small number of employees or run your business on your own, countries with high start-up and maintenance costs (Switzerland, Luxembourg, Liechtenstein) are unlikely to be the best choice for you. In addition to the cost of starting a company, it is also important to consider the costs of maintaining it: the cost of accounting services, the obligation to undergo an audit, the need for local employees and the need for a physical office in the country of incorporation.
    Company control. Before starting a business in Europe and choosing a country to open a company, it is worth paying attention to the corporate legislation of the country you have chosen – in some European countries (Switzerland, Bulgaria) a company with foreign ownership has an obligation to have a local director who is a resident of the country. For some types of business this may be an insignificant and easy to fulfil requirement (you have a partner, a resident of the country in which you fully trust), but for other types of business it can be a significant problem and it is better to try to solve it at the earliest stage, choosing a European country to open a business in which there is no such obligation.
    Confidentiality of information about the company’s beneficiaries. If inaccessibility of data on company beneficiaries is critical for your business, Cyprus and Switzerland will be the preferred choice for opening a company in Europe. It should be borne in mind that in some European countries information on all company members is freely available (Estonia), while in others it can be ordered for a small fee from the Commercial Register or from a private company that has such information.

  11. GlennSaunk表示:

    In recent years, Europe has become one of the most attractive regions for international business due to its stable economic environment, developed infrastructure and favourable legislation. For foreign entrepreneurs wishing to open a company in Europe, one of the key aspects is opening a bank account, which is a prerequisite for business activities. Below is a detailed overview of the process of company registration and opening a bank account in Europe.
    Step 1: Choosing a jurisdiction
    The first step is to choose a country for business registration. Among the popular destinations are Germany, the Netherlands, Estonia and Ireland. Each country has its own peculiarities of business registration, taxation and banking. It is recommended to analyse the market, study local legislation and tax rates, and assess the political and economic stability of the country.
    Step 2: Company registration
    The process of incorporating a company in Europe usually involves submitting an application to the local registration authority, paying registration fees and providing the necessary documents such as incorporation documents, directors’ and shareholders’ details. In some countries, such as Estonia, this process can be fully automated and completed online.

  12. Robertleare表示:

    Ready-made companies with acquired forex license in BVI
    It is always the founder who owns the company, no matter how long it exists
    Fiat – exchange between cryptocurrencies and fiat money on commission
    Acquiring an Existing License
    Articles of association

    crypto license

    Despite the lack of a reliable legal framework for cryptography, crypto companies can legally operate in Slovakia as long as they comply with the general rules. If you are not a Slovak citizen, you will be happy to know that foreign entrepreneurs are subject to the same rules and have access to the same incentives as Slovak citizens.
    Prepaid goods and services and a limited network of goods/services under agreement with the issuer are not included in the definition of e-money. Companies can only apply for an EMI license if they are incorporated in Cyprus and provide at least part of their e-money and/or payment services in Cyprus.
    Operating as a payment institution in Europe means having access to one of the world’s most expansive and economically robust markets, where the EEA’s diversity ensures that payment institutions can connect with a vast customer base and a diverse range of businesses. This makes a European PI license a strategic choice for businesses seeking growth and opportunities in the payment services industry.
    PACKAGE «COMPANY & CRYPTO LICENSE IN SLOVAKIA» INCLUDES:
    In Canada, MSB activities are defined as companies that have at least one of the following operations:

  13. porn表示:

    Oh my goodness! Amazing article dude! Thank you so much, However I am going through troubles with your RSS. I don’t know why I cannot subscribe to it. Is there anybody else having the same RSS problems? Anybody who knows the answer will you kindly respond? Thanx!!

  14. Robertengep表示:

    https://mexstarpharma.online/# medicine in mexico pharmacies

  15. Peterhew表示:

    canadian pharmacy store: legal to buy prescription drugs from canada – safe reliable canadian pharmacy

  16. JeremyPsymn表示:

    https://easyrxcanada.com/# canadian pharmacy com

  17. Pogfff表示:

    buy celecoxib generic – cost indomethacin 50mg indocin 50mg canada

  18. TK88表示:

    Hi there! I could have sworn I’ve visited your blog before but after looking at a few of the posts I realized it’s new to me. Nonetheless, I’m certainly happy I found it and I’ll be bookmarking it and checking back regularly.

  19. Angelita表示:

    Have a look at my web site … Find top-rated certified
    Daycares in your area (Angelita)

  20. This is a topic that’s near to my heart… Cheers! Where can I find the contact details for questions?

  21. Mazrchi表示:

    Привет!
    Стоимость дипломов высшего и среднего образования и процесс их получения
    evolutionist.ru/карта-сайта

  22. AnthonyPress表示:

    best online pharmacies in mexico medication from mexico pharmacy best online pharmacies in mexico

  23. Peterhew表示:

    vipps canadian pharmacy: canadian pharmacy 365 – maple leaf pharmacy in canada

發佈留言

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