AngularJS 1.x Directives vs Components

AngularJS 1.x Directives vs Components

If you ask any angularJS developer what is the most important component of the angular most of them would reply with Directive.

Directives are such an important and powerful part of the angularJS. Because it can manipulate the DOM (Document Object Model) and create new custom elements which are part of the DOM. Up until angular 1.5 angular teams introduce a new element call component. This is a more simplified version of the Directives. Component eventually led the angular to the next level which is Angular 2. Angular 2 is heavily based on component-based structure. But in here we are not gonna talk about Angular 2.

here we are gonna talk about what are the main differences between directives and component, And sort out some of the common misunderstandings about them.

Components are not a replacement for directives

Actually component itself is a special kind of directive. This is much simpler to use compare to directives. For one thing, a component is always elements ('E') where directives can be an element, attribute, class or comment ('E','A','C','M'). Now there's a question coming up. if a component is an element then it should always require a template right? YEP, a template is a mandatory property to a component whereas template is not mandatory in directives.   

Isolated scope

component consist with the scope but unlike directives, the scope is isolated. Directives can modify DOM or data that is outside of their scope, but the component can only access data within isolated scope. The main reason to avoid adding these features to a component is to prevent additional complexity. Because when the problem occurs it is very difficult to identify which part of the application responsible for modifying data.

No more Dom Manipulation

Speaking of DOM manipulation, a component doesn't have a "link" function. in angular docs its clearly state that if you want to perform pre-link, compile then go with the directives. in the component, those features are not available.

Component-based structure

Basically, the component-based structure allows set of components to existing in same space yet interact independently. As an example, let's take linkedIn. LinkedIn chat is one component, a comment is another one. The news feed is another special component where updates real time. They all exist in the same space but independent from other components. Angular components also follow the component-based structure. 

With the help of the component, we can divide the application into smaller reusable components. Directives in the other hand more focus on the behaviors. it can add behaviors to existing DOM elements. So the bottom line is that the Angular components are reusable components while directives use to create reusable behaviors.

Communication between other components. 

Directives have the ability to communicate with other directive controllers.This can be achieved in a component by providing an object mapping for the require property. The object can be assigned to require property where the key is a property name that binds the required controller. Take this example.

.component('myPane', {
  require: {
    tabsCtrl: '^myTabs'
  },
  controller: function() {
    this.$onInit = function() {
      this.tabsCtrl.addPane(this);
      console.log(this);
    };
  },
  templateUrl: 'my-pane.html'
});

Here myPane component can access the myTabs component controller through the this.tabsCtrl property. Note that the required controllers will not be available during the instantiation of the controller, but they are guaranteed to be available just before the $onInit method is executed. Let's talk about $onInit function next, under “Component life cycle”

Component life cycle

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the lifecycle hook. Directives are consisted with compile, link and controller hooks to complete its life cycle. A component has a controller but no link functions since it’s primary use is to create reusable components. addition to that component has its own lifecycle hooks.These are methods that will be called at certain points in the life of the component.

●    $onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized.

Another nice thing about $onInit is that we can access controllers of parent components on our own component’s controller, as those are exposed to it for inter-component communication. This means it’s not even necessary anymore to have a link() function to access other directive controllers. 

In the previous example, we’d build a myTabs component and a myPane component, where the latter needs access to the TabsController to register itself on it, we can simply ask for it using the require property and call it directly via the controller instance. 

●    $onChanges() - Called whenever one-way bindings are updated

●    $onDestroy()  - Called on a controller when its containing scope is destroyed 

These are only few life cycle methods available in the Components. You can check the docs for more information about the life cycle methods.

Conclusion

In here we mainly focus on components and main differences between components and directives. I hope you guys get an idea about when to or when not use the components as well as directives. 

from my understanding, a directive is about to behave, a component is a reusable object

Thomas Trung Nguyen

I am a Software Engineer with 15 years of experience, including 4 years in blockchain and crypto (since 2021). My work is focused on blockchain core protocols, advanced cryptography and machine learning.

6y

Nice article. Thanks a lot!

Like
Reply
Tanmay Awasthi

SDE IV at Groupon | Frontend Engineer | JavaScript, React Enthusiast

6y

Great explanation. Thanks! 

Like
Reply
Dinesh Thanam

Software Engineer at Cognizant

6y

Nice explanations

Like
Reply

To view or add a comment, sign in

More articles by Sachila Ranawaka

  • Extension Methods

    Extension method allows us to add new methods to types without creating a new instance or modifying the original type…

  • Structural Directives

    Have you ever encountered an error while trying to use the both *ngIf and *ngFor in the same element? If you are a…

  • Angular 5 what's new

    Yes, you read that right. Earlier this November Google released the latest version for the angular which is angular 5.

  • SSL configuration on apache.

    What is SSL SSL (Secure Sockets Layer) is a standard security protocol which establishes encrypted links between a web…

    9 Comments
  • Understanding Observables

    The observable is a brand new concept release in ES7. In this article, we gonna dig deep into the observable.

  • AngularJS 1.x Understanding Filters

    According to the angular docs ‘Filters format the value of an expression for display to the user’. It’s little…

  • AngularJS vs Angular 2

    One of the frequent questions I see in the community these days is “Whether I should learn angular js 1 or angular 2”…

    2 Comments
  • Javascript Closures

    Closures in the javascript mainly use for handle privacy of object data. In javascript MDN, it describes closure as a…

  • TypeScript Introduction

    Typescript is one of the bigger milestones that hits to the JavaScript after the ECMAScript 6. So what is TypeScript?…

  • Promise anti-pattern

    Promises in angularJS is basically used to handle asynchronous tasks. Promises are easy to understand when you are…

Insights from the community

Others also viewed

Explore topics