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

51,646 Responses

  1. LloydNoice表示:

    https://kampharm.shop/# cheapest Kamagra Kam Pharm

  2. infulky表示:

    Article FDA Approved Drug Products Solifenacin Succinate Tablets Link Cayman Chemicals Solifenacin MSDS Link buy priligy 60 pentobarbital decreases levels of liothyronine by increasing metabolism

  3. DennishIp表示:

    buy gabapentin online: Buy gabapentin for humans – gabapentin GabaPharm

  4. JeffreyVog表示:

    Chainlist: Simplifying Blockchain Connections
    In the evolving world of cryptocurrencies, Chainlist emerges as a pivotal tool for users looking to seamlessly interact with various blockchain networks. Understanding what Chainlist offers and how it operates can significantly enhance your crypto experience.
    Chain List
    What is Chainlist?
    Chainlist is a user-friendly platform designed to facilitate easy connections between crypto wallets and blockchain networks. It caters to both new and experienced crypto users by providing a comprehensive list of blockchain networks that can be accessed with just a few clicks.

    Key Features of Chainlist
    Extensive Network List: Chainlist provides access to a vast selection of blockchain networks, ensuring users can connect to the network of their choice with ease.
    Seamless Wallet Integration: With Chainlist, users can connect their crypto wallets such as MetaMask efficiently, facilitating quick and secure transactions.
    User-Friendly Interface: The platform’s intuitive design ensures a smooth user experience, making it easy for beginners to navigate through different blockchain networks.
    Why Use Chainlist?
    Using Chainlist can considerably enhance your blockchain interactions by simplifying the network connection process. Here are some reasons why you should consider using Chainlist:

    Reduce Errors: Minimize the chances of manually inputting incorrect network details.
    Save Time: Quickly switch between networks without having to tweak wallet settings manually.
    Broaden Access: Easily explore lesser-known or new blockchains without extensive setup procedures.
    How to Connect Your Wallet Using Chainlist
    Visit the .
    Search for the blockchain network you wish to connect with.
    Click on the “Connect Wallet” button next to your desired network.
    Authorize the connection through your wallet’s interface, such as MetaMask.
    Begin your crypto transactions on the selected network.
    In summary, Chainlist serves as a crucial bridge between crypto users and blockchain networks, offering a simplified connection process that enhances both functionality and accessibility.

    Welcome to Chain List: Your Comprehensive Blockchain Directory
    Are you looking for a simple way to connect to different blockchain networks? Chain List offers a seamless solution, allowing users to discover and connect to thousands of blockchain networks rapidly and efficiently.

    What is Chain List?
    Chain List is a user-friendly platform designed to help cryptocurrency enthusiasts, developers, and investors explore various blockchain networks. With a focus on decentralized technologies, it provides a vast database of available networks, offering quick, reliable connections for users.

  5. RobertHam表示:

    https://erepharm.com/# cheapest ed pills ere pharm

  6. RobertSam表示:

    What is DeBridge Finance?
    DeBridge Finance is an innovative solution designed to facilitate seamless cross-chain blockchain operations. It empowers developers and users by allowing the transfer of data and assets across different blockchain networks efficiently and securely.
    Debridge Finance
    Key Features of DeBridge Finance
    DeBridge Finance stands out due to its remarkable features which include:

    Interoperability: The platform provides effective interoperability between multiple blockchains, eliminating the boundaries that exist.
    Security: By leveraging advanced security protocols, DeBridge ensures the safe transit of data and assets.
    Scalability: It is designed to handle a growing number of transactions without compromising on performance.
    How Does DeBridge Finance Work?
    DeBridge Finance operates through a combination of smart contracts and decentralized communication protocols. These components work together to authenticate and execute cross-chain data and asset transfers swiftly and securely.

    Smart Contracts
    The platform utilizes smart contracts to automate processes and ensure trustless operations across different chain environments.

    Decentralized Communication
    Communication across blockchains is made possible through a decentralized message protocol, enabling effective data sharing.

    Benefits of Using DeBridge Finance
    Choosing DeBridge Finance for cross-chain operations brings several advantages:

    Cost-Effectiveness: By integrating various blockchains, it reduces the cost and complexity of using multiple networks.
    Developer-Friendly: Offering robust tools and resources, DeBridge makes it easier for developers to build cross-chain applications.
    Enhanced User Experience: Users benefit from smoother transactions without the need to switch between different network interfaces.

  7. StevenLoN表示:

    Unlock the Power of Eigenlayer
    As the blockchain landscape evolves, Eigenlayer emerges as a beacon of innovation, offering robust solutions to enhance blockchain security and customization. But what exactly does Eigenlayer bring to the table?
    eigenlayer claim
    Revolutionizing Blockchain Security
    Security is paramount in the blockchain world, and Eigenlayer takes this seriously. By leveraging state-of-the-art technology, Eigenlayer provides an unparalleled layer of protection for blockchain protocols. This ensures that transactions are not only secure but also reliable.

    Advanced Encryption: Protects data integrity and confidentiality.
    Scalable Solutions: Ensures that security measures grow with your network’s demand.
    Customization like Never Before
    One of the most compelling features of Eigenlayer is its customization capabilities. Understanding that each blockchain project has unique needs, Eigenlayer offers a flexible architecture allowing projects to tailor solutions to their specific requirements.

    Modular Design: Adapts to various use cases without sacrificing performance.
    Interoperability: Seamlessly integrates with existing blockchain systems.
    Empowering Blockchain Ecosystems
    By providing these advanced features, Eigenlayer doesn’t just offer protection and customization; it empowers blockchain developers to push the boundaries of what’s possible. With Eigenlayer, the limitations often faced in blockchain scalability and security are becoming a thing of the past.

    Whether you are a developer seeking better security solutions or an entrepreneur aiming to launch your blockchain project with tailor-made features, Eigenlayer provides the tools and the support you need to succeed in the competitive digital landscape.

    Explore the potential of Eigenlayer today, and step into the future of blockchain technology with a partner committed to your success.

  8. AndreFuh表示:

    Welcome to Stargate Finance
    Stargate Finance is revolutionizing the way you engage with decentralized financial services. Our platform is designed to offer a secure, efficient, and user-friendly experience for all your financial needs in the world of decentralized finance.
    stargate bridge
    Why Choose Stargate Finance?
    In the rapidly evolving world of decentralized finance (DeFi), Stargate Finance stands out as a trusted platform due to its innovative solutions and user-centric approach. Here are some reasons to choose us:

    Seamless integration with major blockchain ecosystems
    Advanced security protocols to protect your assets
    User-friendly interface for beginners and experts alike
    Core Features of Stargate Finance
    Stargate Finance provides a variety of features to enhance your DeFi experience, including:

    Cross-Chain Transactions: Safely send and receive assets across different blockchain networks.
    Liquidity Provision: Earn rewards by providing liquidity to various liquidity pools.
    Yield Farming: Maximize your returns through strategic yield farming opportunities.
    How to Get Started
    Getting started with Stargate Finance is simple:

    Visit our official website and create an account.
    Connect your crypto wallet and fund your account with preferred assets.
    Explore our platform’s features and start managing your investment portfolio.

  9. FreddieDIG表示:

    How to Securely Log Into Debank: A Step-by-Step Guide
    Logging into your Debank account is the first step towards managing your DeFi portfolio. Ensuring that your login credentials remain secure is crucial for protecting your investments. In this guide, we’ll walk you through the process of logging into Debank safely and efficiently.
    debank profile search
    Step 1: Visit the Official Debank Website
    Start by navigating to the official Debank website. Avoid using search engine results to prevent phishing attacks. The URL should be .

    Step 2: Click on the Login Button
    On the homepage, locate the Login button usually positioned at the top right corner of the page. Click on it to proceed to the login page.

    Step 3: Enter Your Credentials
    Input your registered email address and password. Ensure your password is strong, combining letters, numbers, and symbols to enhance security.

    Step 4: Two-Factor Authentication
    It’s recommended to enable Two-Factor Authentication (2FA) for an additional security layer. This can be done using an app like Google Authenticator. Enter the code generated by your 2FA app to continue.

    Step 5: Secure Your Account
    Regularly Update Your Password: Change your password every 3-6 months.

    Use a Password Manager: Helps store and recall complex passwords without difficulty.

    Monitor Account Activity: Regularly check for any unauthorized access or activity.

    Additional Tips for Staying Safe Online
    Be vigilant about where you input your credentials. Always ensure that you have a secure and reliable internet connection. Avoid accessing your Debank account on public Wi-Fi networks, which might be unsecured.

    By following these guidelines, you can enhance the security of your Debank login process and safeguard your investments effectively. Stay aware of the latest security practices and updates from Debank to keep your account secure.

  10. Thomasdag表示:

    Base is for everyone.
    Base Bridge is a cutting-edge solution facilitating smooth transfers between different blockchain networks. By creating a seamless link, it reduces the complexity and cost of blockchain transactions.
    base bridge eth
    What is Base Bridge?
    Base Bridge is a cutting-edge solution facilitating smooth transfers between different blockchain networks. By creating a seamless link, it reduces the complexity and cost of blockchain transactions.

    Key Features of Base Bridge
    Interoperability: Connects multiple blockchain networks, allowing for smooth asset exchange.

    Cost Efficiency: Reduces transaction fees significantly.

    Security: Leverages advanced encryption to protect transactions.

    Scalability: Easily adapts to increasing volumes of transactions without compromising speed.

    Benefits of Using Base Bridge
    Incorporating Base Bridge into your blockchain strategy offers numerous benefits:

    Simplified Transactions: Eliminates the need for complicated cross-chain processes.

    Faster Settlements: Enjoy quicker transaction confirmations.

    Cost-Effective Operations: Lower fees mean more sustainable transactions.

    Improved Security: Benefit from enhanced protection against fraud and hacking.

  11. raketaigra表示:

    Попробуйте скачать Лаки джет и начните свой путь к победе.

  12. JeromeTox表示:

    Optimize your trades across hundreds of DEXes on multiple networks
    1inch wallet
    1inch Exchange is a decentralized exchange aggregator. It searches multiple DEXs to find the most efficient path for your trade, thus minimizing costs and maximizing returns. By splitting your transaction into parts and executing them across different platforms, 1inch achieves the best possible market rates.
    Explore the 1inch Network: The Future of DeFi
    The 1inch Network stands at the forefront of decentralized finance (DeFi), offering traders highly efficient cryptocurrency swap solutions across multiple platforms. This introduction to 1inch will guide you through its features, benefits, and the impact it’s making in the crypto trading ecosystem.

    What Makes 1inch Unique?
    1inch is renowned for being a decentralized exchange aggregator. It sources liquidity from various exchanges to offer users the best possible rates. By splitting orders across multiple platforms, 1inch minimizes slippage and maximizes the value from each trade.

    Core Components of 1inch
    1inch Aggregation Protocol: A sophisticated routing mechanism that finds the most efficient swapping paths across multiple decentralized exchanges.

    1inch Liquidity Protocol: An automated market maker (AMM) that operates in a gas-efficient way, allowing users to provide liquidity and earn a portion of trades.

    1inch DAO: A decentralized autonomous organization that allows token holders to participate in the governance of the network.

    Benefits of Utilizing 1inch
    By tapping into 1inch’s ecosystem, traders gain access to:

    Optimal Rates: The cutting-edge algorithm ensures you’re always getting the best prices available.

    Security and Trust: As a non-custodial service, your funds remain under your control at all times.

    Reduced Slippage: Smart order routing minimizes discrepancies in pricing.

    Community-Driven: Participate in the governance processes thanks to the 1inch DAO.

  13. FreddyTOm表示:

    Phantom Wallet Extension | Official Website
    phantom wallet download
    The Phantom Wallet is revolutionizing the way users handle digital currencies. Designed for the Solana network, it offers security and ease for both beginners and experienced users. Dive into its features and learn how it can elevate your crypto management.

    Why Choose Phantom Wallet?
    When it comes to managing digital assets, security is paramount. Phantom Wallet provides top-tier security features, ensuring users’ assets remain safe from threats.

    Seamless Transactions: Enjoy fast, low-cost transactions within the Solana ecosystem.

    User-Friendly Interface: Navigate easily with an intuitive design that suits all user skill levels.

    Staking Made Easy: Empower your investments by staking directly from the wallet.

    Getting Started with Phantom Wallet
    Setting up your Phantom Wallet is simple. Follow these steps:

    Download and install the Phantom extension from a trusted source.

    Create a new wallet or import an existing one by following the prompts.

    Backup your secret recovery phrase in a safe location.

    Once set up, you can start managing your tokens effortlessly.

    Phantom Wallet Features
    Beyond security, Phantom Wallet offers:

    Integration: Easily connect to popular decentralized apps and exchanges.

    Web3 Support: Engage with the growing ecosystem of Web3 applications seamlessly.

    Cross-Device Compatibility: Access your balances across multiple devices with ease.

  14. CurtisCem表示:

    gabapentin buy gabapentin india buy gabapentin

  15. LloydNoice表示:

    https://gabapharm.com/# buy gabapentin india

  16. Hello there, There’s no doubt that your web site could be having browser compatibility problems. Whenever I take a look at your site in Safari, it looks fine however when opening in Internet Explorer, it has some overlapping issues. I simply wanted to provide you with a quick heads up! Apart from that, fantastic site.

  17. Antoineeraft表示:

    О компании «Саранск-Климат»
    кондиционер
    Установка кондиционеров или сплит-систем — это реальная возможность сэкономить на энергоносителях до 50%. При этом Вы гарантируете комфортный обогрев и охлаждение в любое время года. Специалисты нашей компании подберут лучшее оборудование, подходящее под задачи клиента.

    Вся климатическая техника ввозится в Россию официально и проходит обязательную сертификацию. Инструкции и оборудование имеют русскоязычную поддержку. Компания предоставляет официальную гарантию на всю климатическую технику без исключения.

    Для всех покупателей доступны сервисы доставки, установки, обслуживания климатической техники.
    На станице опубликованы актуальные данные о компании «Саранск-Климат» в Саранске.

    Кондиционеры и сплит-системы с доставкой и установкой в Саранске
    Кондиционеры и сплит-системы Вы можете выгодно купить по низким ценам на сайте компании «Саранск-Климат» в Саранске .

  18. TimothyDuawl表示:

    Why Thailand is making it easier for travelers to stay longer
    Пхукет
    Maybe you want to escape the winter months at home, opting instead to take care of your business on a laptop from the comfort of your rented Phuket villa as you gaze over the Andaman Sea. Or perhaps you’re ready to step into the ring and embark on a new career as a Muay Thai fighter.

    Either way, Thailand has you covered.

    The popular Southeast Asia destination recently introduced a new five-year visa targeted at remote workers and other travelers looking to stay in the kingdom for extended periods.

    According to a statement issued by the Thai prime minister’s office, the Destination Thailand Visa (DTV) will allow eligible travelers a period of stay up to 180 days per visit, on a multiple-entry basis, within five years. (This means they will need to leave the country when their 180 days are up, and the time resets when they re-enter.)
    The government statement says the visa is open to several categories of remote workers, including digital nomads and freelancers. It’s also aimed at those looking to visit to engage in activities such as Muay Thai training or Thai cooking classes, or come for extended medical treatments.

    To apply, travelers need to show evidence that they have a minimum of 500,000 baht (about $13,800) in funds, as well as documents to support the purpose of their visit, such as a letter from a medical center or proof of employment

  19. Good day! Do you know if they make any plugins to assist
    with SEO? I’m trying to get my website to rank for some targeted keywords
    but I’m not seeing very good results. If you know of any please share.

    Kudos! I saw similar art here: Eco wool

發佈留言

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