search
HomeWeb Front-endJS TutorialHow to implement mvvm style tabs in Angularjs? case + code

We know that tabs are one of the most commonly used effects in modern web pages. This time we will show you how to implement mvvm-style tabs in Angularjs? Case + code, the following is a practical case, let’s take a look.

The focus of this article is to use angularjs, a very popular mvvm framework, to achieve the tab effect. Before that, let’s move out our commonly used jquery implementation.

1. jquery implements simple and crude tab effect

var nav = $(".tabs");//tab切换var box = $(".box");//容器nav.on("click", function(){ //点击事件
  var this_index=$(this).index();
  $(this).addClass("active").siblings().removeClass("active");
  box.eq(this_index).show().siblings().hide();
});

Only the core part of js is given here, and html and css will not be described in detail.
The above code implements the tab effect simply and crudely. It uses the click event to obtain elem.index(), and connects the index and the container to control the display and hiding.

2. Angularjs implements a simple tab effect

Html part

<section ng-app="myApp">
       <div class="tabs tabs-style" ng-controller="TabController as tab">
         <nav>
           <ul>
             <li ng-class="{&#39;current&#39;:tab.isSet(1)}">
               <a href="#" ng-click="tab.setCurrent(1)"><span>Home</span></a></li>
             <li ng-class="{&#39;current&#39;:tab.isSet(2)}">
               <a href="#" ng-click="tab.setCurrent(2)"><span>Work</span></a></li>
             <li ng-class="{&#39;current&#39;:tab.isSet(3)}">
               <a href="#" ng-click="tab.setCurrent(3)"><span>Blog</span></a></li>
             <li ng-class="{&#39;current&#39;:tab.isSet(4)}">
               <a href="#" ng-click="tab.setCurrent(4)"><span>About</span></a></li>
             <li ng-class="{&#39;current&#39;:tab.isSet(5)}">
               <a href="#" ng-click="tab.setCurrent(5)"><span>Contact</span></a></li>
           </ul>
         </nav>
         <div class="content">
           <section id="section-1"  ng-show="tab.isSet(1)">
             <p>1</p>
           </section>
           <section id="section-2"  ng-show="tab.isSet(2)">
             <p>2</p>
           </section>
           <section id="section-3" ng-show="tab.isSet(3)">
             <p>3</p>
           </section>
           <section id="section-4" ng-show="tab.isSet(4)">
             <p>4</p>
           </section>
           <section id="section-5" ng-show="tab.isSet(5)">
             <p>5</p>
           </section>
         </div>
       </div>
   </section>

css part (here for the convenience of us using Less syntax, children can customize css to achieve personalized effects )

* {  margin: 0;  padding: 0;
}body {  background: #e7ecea;  font-weight: 600;  font-family: &#39;Raleway&#39;, Arial, sans-serif;  text-align: center;
}a {    color: #2CC185;    text-decoration: none;    outline: none;
  
    &:hover {    color: #74777b;
    }
}.tabs {  position: relative;  width: 100%;  margin: 30px auto 0 auto;
  nav {
    ul {      position: relative;      display: flex;      max-width: 1200px;      margin: 0 auto;      list-style: none;      flex-flow: row wrap;      justify-content: center;
      
        li {          flex: 1;
          
          &.current a {            color: #74777b;
          }
        }
      }
    }  
    a {      display: block;      position: relative;      overflow : hidden;      line-height: 2.5;
      
      span {        vertical-align: middle;        font-size: 1.5em;
      }
    }
}.content {  position: relative; 
  
  section {    /* display: none; */
    margin: 0 auto;    max-width: 1200px;
    &.content-current {      /* display: block; */
    }    
    p {      color: rgba(40,44,42, 0.4);      margin: 0;      padding: 1.75em 0;      font-weight: 900;      font-size: 5em;      line-height: 1;
    }
  }
}.tabs-style {
  nav {    /* background: rgba(255,255,255,0.4); */
    
    ul li {
      a {        overflow: visible; 
        border-bottom: 1px solid rgba(0,0,0,0.2);        -webkit-transition: color 0.2s;        transition: color 0.2s;
      }
    }    
    ul li.current a{
      &:after, &:before {        content: &#39;&#39;;        position: absolute;        top: 100%;        left: 50%;        width: 0;        height: 0;        border: solid transparent;
        }
      &:after {        margin-left: -10px;        border-width: 10px;        border-top-color: #e7ecea;
      }
      &:before {        margin-left: -11px;        border-width: 11px;        border-top-color: rgba(0,0,0,0.2);
      }
    }
  }
}

js part

angular.module(&#39;myApp&#39;, [])
  .controller(&#39;TabController&#39;, function() {    this.current = 1;  
  this.setCurrent = function (tab) {    this.current = tab;
  };  
  this.isSet = function(tab) {    return this.current == tab;
  };
});

The final effect is as shown below:

How to implement mvvm style tabs in Angularjs? case + code

Through the above code, we can find that the core of the implementation is Angularjs's built-in ng-class, ng-click, and ng-show instructions. In layman's terms: The default value of current data is defined in the controller as 1. ng-click gives the click event custom function to change the current data. ng-class binds conditions by getting the value of current to give The current style is added to the currently selected index, and the container also obtains the current data in the controller and displays and hides it through ng-show control.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

How to debug different versions of nodejs with different versions of vscdoe

##Vuejs webp supports image plug-in development

The above is the detailed content of How to implement mvvm style tabs in Angularjs? case + code. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools