Home Web Front-end JS Tutorial An in-depth explanation of the use of custom directives in AngularJS_AngularJS

An in-depth explanation of the use of custom directives in AngularJS_AngularJS

May 16, 2016 pm 03:53 PM
angularjs

AngularJS’s custom instructions are your own instructions, plus the native core functions that the compiler runs when compiling the DOM. This can be difficult to understand. Now, let's say we want to reuse some specific code across different pages in our application without duplicating the code. Then, we can simply put this code into a separate file and call the code using the custom directive instead of typing it out over and over again. Such code is easier to understand. There are four types of custom directives in AngularJS:

  1. Element command
  2. Attribute command
  3. CSS class directive
  4. Comment command

Before implementing them in our existing app, let’s take a look at what custom directives look like:

Element Command

Write the following tag in html, which is used to place code snippets. When we want to use a specific code, we include the code using the above tag.

<guitar-reviews> ... </guitar-reviews>
Copy after login

In the JS file, use the following lines of code to make the above angularJS custom directive effective.

app.directive('guitarReviews', function() {
 return {
  restrict  : 'E', // used E because of element 
  templateUrl : 'custom-directives/reviews.html'
 };
});
Copy after login

Code explanation:

Like app.controller, we first define app.directive, and then define guitarReview, which is the element tag name used in html. But have you noticed that guitar-review and guitarReviews are different? This is because the hyphen in guitar-reviews is converted to camel case, so it becomes guitarReviews in the JS file. The next step is the anonymous function that is returning parameters. restrict: 'E' means that we are defining a custom element directive, and templateUrl points to the code snippet file to be included.

Attribute directive

Type the following attributes in the html tag of the html file. This tag is used to hold code snippets. When we want to use a specific piece of code, we just type a tag like this to include the code.

<div guitar-reviews> ... </div>
Copy after login

In the JS file, use the following code to make the above angularJS custom directive effective.

app.directive('guitarReviews', function() {
 return {
  restrict  : 'A', // used A because of attribute 
  templateUrl : 'custom-directives/reviews.html'
 };
});
Copy after login

Note: AngularJS recommends that you use simple css and ordinary comments instead of CSS and comments in custom directives.

Now let’s implement custom commands in the app. You can download the project files here. I put the code for the reviews part into a separate file, then assigned the code snippet to an element, and finally used it in the details.html page.

First step

Create a new folder named cDirectives under the specified folder to store customized instructions. Then, create a reviews.html file in this folder to hold the user's reviews. At this point, your folder hierarchy looks like this:

2015618121816801.png (152×250)

Step 2

Cut the review section in details.html and add the tag as follows:

2015618121835496.png (1024×573)

Step 3

Copy the code you cut in the details.html page to reviews.html as shown below:

<!-- Review Tab START, it has a new controller -->
<div ng-show="panel.isSelected(3)" class="reviewContainer" ng-controller="ReviewController as reviewCtrl" >
 
<!-- User Reviews on each guitar from data.json - simple iterating through guitars list -->
<div class="longDescription uReview" ng-repeat="review in guitarVariable[whichGuitar].reviews"> 
  <h3>Review Points: {{review.star}} </h3>
  <p> {{review.body}} ~{{review.name}} on <date>{{review.createdOn | date:'MM/yy'}} </p>
</div><!-- End User Reviews -->
 
<!-- This is showing new review preview-->
<div ng-show="add === 1" class="longDescription uReview" > 
  <h3>Review Points: {{reviewCtrl.review.star}} <span ng-click="add=0">X</span></h3>
  <p> {{reviewCtrl.review.body}} ~ {{reviewCtrl.review.name}} </p>
</div>
 
<!-- Add new Review to specific guitar - click this link to show review adding pannel -->
<a href ng-click="add=1" class="addReviewLink">Add review</a>  
 
<!-- form validates here using form name and .$valid and on submission we are going to addReview function with guitarID -->
<form class="reviewForm" name="reviewForm" ng-submit="reviewForm.$valid && reviewCtrl.addReview(guitarVariable.indexOf(guitarVariable[whichGuitar]))" novalidate ng-show="add===1" >
  <div>
    Review Points: 
    <!-- ng-option here is setting options, cool&#63; -->
    <select ng-model="reviewCtrl.review.star" ng-options="point for point in [5,4,3,2,1]" required >    
    </select>
    Email: 
    <input type="email" ng-model="reviewCtrl.review.name" required>
    <button type="submit">Submit</button>
    </div>
    <textarea placeholder="Enter your experience with this guitar..." ng-model="reviewCtrl.review.body"></textarea>
</form><!-- END add new review -->
</div><br /><!-- END Review Tab -->
Copy after login


Step 4

It is now possible to add actions in the user-reviews tag. Let’s open controller.js and add the following code:

GuitarControllers.directive('userReviews', function() {
 return {
  restrict  : 'E', // used E because of element 
  templateUrl : 'partials/cDirectives/reviews.html'
 };
});
Copy after login

Code explanation:

Our directive here becomes userReviews (in camel form) and the hyphen is gone. Below we can say that when it is called the file in templateURL is loaded and the directive is restricted to element E.

We just customized a directive. Even though it looks like nothing has changed in our application, our code is now better planned than before. Can you customize directives for descriptions and specifications? Try it yourself.

Statement of this Website
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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Build web applications using PHP and AngularJS Build web applications using PHP and AngularJS May 27, 2023 pm 08:10 PM

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

Use PHP and AngularJS to develop an online file management platform to facilitate file management Use PHP and AngularJS to develop an online file management platform to facilitate file management Jun 27, 2023 pm 01:34 PM

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

How to use AngularJS in PHP programming? How to use AngularJS in PHP programming? Jun 12, 2023 am 09:40 AM

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.

Build a single-page web application using Flask and AngularJS Build a single-page web application using Flask and AngularJS Jun 17, 2023 am 08:49 AM

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

Introduction to the basics of AngularJS Introduction to the basics of AngularJS Apr 21, 2018 am 10:37 AM

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

How to use PHP and AngularJS for front-end development How to use PHP and AngularJS for front-end development May 11, 2023 pm 05:18 PM

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

See all articles