Thứ Hai, 11 tháng 7, 2016

Mastering AngularJS Directives

Directives are one of the most powerful components of AngularJS, helping you extend basic HTML elements/attributes and create reusable and testablecode. In this tutorial, I will show you how to use AngularJS directives with real-life best practices. 
What I mean here by directives is mostly custom directives during the tutorial. I will not try to teach you how to use built-in directives like ng-repeatng-show, etc. I will show you how to use custom directives to create your own components. 
  1. Simple Directives
  2. Directive Restrictions
  3. Isolated Scope
  4. Directive Scopes
  5. Directive Inheritance
  6. Directive Debugging
  7. Directive Unit Testing
  8. Directive Scope Testing
  9. Conclusion
Let say that you have an eCommerce application about books and you are displaying specific book detail in several areas, such as the comments, user profile pages, articles, etc. Your book detail widget may be like below:
In this widget there is a book image, title, description, comments, and rating. Collecting that information and putting in a specific dom element may be hard to do in every place you want to use it. Let's widgetize this view by using an AngularJS directive. 
directive function has been used in the above example to create a directive first. The name of the directive is bookThis directive returns an object, and let's talk a bit about this object. restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment). You can see the usage of each respectively below.
TypeUsage
A<div book></div>
C<div class="book"></div>
E<book data="book_data"></book>
M<!--directive:book -->
scope is for managing the directive scope. In the above case, book data is transferred to the directive template by using the "=" scope type. I will talk about in detail about scope in the following sections. templateUrl is used for calling a view in order to render specific content by using data transferred to the directive scope. You can also use template and provide HTML code directly, like this:
In our case, we have a complicated HTML structure, and that is why I chose the templateUrl option.
Directives are defined in the JavaScript file of your AngularJS project and used in the HTML page. It is possible to use AngularJS directives in HTML pages as follows:
In this usage, the directive name is used inside standard HTML elements. Let say that you have a role-based menu in your eCommerce application. This menu is formed according to your current role. You can define a directive to decide whether the current menu should be displayed or not. Your HTML menu may be like below:
and the directive as follows:
If you use the restricted directive in the menu element as an attribute, you can do an access level check for each menu. If the current user is not authorized, that specific menu will not be shown. 
So, what is the link function there? Simply, the link function is the function that you can use to perform directive-specific operations. The directive is not only rendering some HTML code by providing some inputs. You can also bind functions to the directive element, call a service and update the directive value, get directive attributes if it is an E type directive, etc.
You can use the directive name inside HTML element classes. Assuming that you will use the above directive as Cyou can update the directive restrict asC and use it as follows:
Each element already has a class for styling, and as the restricted class is added it is actually a directive.
You don't need to use a directive inside an HTML element. You can create your own element by using an AngularJS directive with an E restriction. Let's say that you have a user widget in your application to show usernameavatar, andreputation in several places in your application. You may want to use a directive like this:
The HTML code will be:
In the above example, a custom element is created and some attributes are provided like usernameavatar, and reputation. I want to draw attention to the link function body. Element attributes are assigned to directive scope. The first parameter of the link function is the scope of the current directive. The third parameter of the directive is the attribute object of the directive, which means that you can read any attribute from the custom directive by usingattrs.attr_name. Attribute values are assigned to the scope so that they are used inside the template. 
Actually, you can do this operation in a shorter way, and I will talk about that later. This example is for understanding the main idea behind usage.
This usage is not very common, but I will show how to use it. Let's say that you need a comment form for your application to use in many places. You can do that by using the following directive:
And in the HTML element:
Every directive has its own scope, but you need to be careful about the data binding with the directive declaration. Let say that you are implementing thebasket part of your eCommerce application. On the basket page you have items already added here before. Each item has its amount field to select how many items you want to buy, like below:
Simple Cart
Here's the directive declaration:
And in order to display three items in HTML:
The problem here is that whenever you choose the amount of the desired item, all the amount sections of the items will be updated. Why? Because there is two-way data binding with a name count, but scope is not isolated. In order to isolate scope, just add scope: {} to the directive attribute in the return section:
This leads your directive to have its own isolated scope so two-way data binding will occur inside this directive separately. I will also mention about the scope attribute later.
The main advantage of the directive is that it's a reusable component that can be used easily—you can even provide some additional attributes to that directive. But, how is it possible to pass additional value, binding, or expression to a directive in order for data to be used inside the directive?
"@" Scope: This type of scope is used for passing value to the directive scope. Let's say that you want to create a widget for a notification message:
and you can use:
In this example, the message value is simply assigned to the directive scope. The rendered HTML content will be:
"=" Scope: In this scope type, scope variables are passed instead of the values, which means that we will not pass {{message}}, we will pass message instead. The reason behind this feature is constructing two-way data binding between the directive and the page elements or controllers. Let's see it in action.
In this directive, we are trying to create a widget for displaying comment text input to make a comment for a specific book. As you can see, this directive requires one attribute text to construct two-way data binding between other elements on the pages. You can use this on the page:
This will simply show a textbox on the page, so let's add something more to interact with this directive:
Whenever you type something in the first text box, it will be typed also in the second text box. You can do that vice versa. In the directive, we passed the scope variable commentText instead of the value, and this variable is the data binding reference to the first text box. 
"&" Scope: We are able to pass the value, and reference to directives. In this scope type we will have a look at how to pass expressions to the directive. In real-life cases, you may need to pass a specific function (expression) to directives in order to prevent coupling. Sometimes, directives do not need to know much about the idea behind the expressions. For example, a directive will like the book for you, but it doesn't know how to do that. In order to do that, you can follow a structure like this:
In this directive, an expression will be passed to the directive button via thelike attribute. Let's define a function in the controller and pass it to the directive inside the HTML.
This will be inside the controller, and the template will be:
likeFunction() comes from the controller and is passed to the directive. What if you want to pass a parameter to likeFunction()? For example, you may need to pass a rating value to the likeFunction(). It is very simple: just add an argument to the function inside the controller, and add an input element to the directive to require start count from the user. You can do that as shown below:
As you can see, the text box comes from the directive. The text box value is bound to the function argument like like({star: starCount})star is for the controller function, and starCount for the textbox value binding. 
Sometimes, you may have a feature that exists in several directives. They can be put in a parent directive so that they are inherited by the child directives. 
Let me give you a real-life example. You want to send statistical data whenever customers move their mouse cursor to the top of a specific book. You can implement a mouse click event for the book directive, but what if it will be used by another directive? In this case, you can use inheritance of the directives like below:
This is a parent directive to be inherited by child directives. As you can see there is a controller attribute of the directive using the "as" directive. Let's define this controller also:
In this controller, we are simply setting a controller instance of the variablebookType by using child directives. Whenever you click a book or magazine, the type of element will be sent to the back-end service (I used an alert function just to show the data). How will child directives be able to use this directive?
As you can see, child directives use the require keyword to use the parent directive. And one more important point is the fourth argument of the link function in the child directives. This argument refers to the controller attribute of the parent directive that means the child directive can use the controller function setBookType inside the controller. If the current element is an eBook, you can use the first directive, and if it is a magazine, you can use the second one:
Child directives are like a property of the parent directive. We have eliminated the usage of the mouse-click event for each child directive by putting that section inside the parent directive.

Không có nhận xét nào:

Đăng nhận xét