Purpose of $element and $ attrs in component controllers with angularJS components 1.5

That's a great question. And I have a simple answer for it.

They take place in components just because Component is syntax sugar around of directive.

Before angular added Components, I was using some kind of component syntax for directives, it was like a convention, that in our project we have two kinds of directives, one is responsible for DOM manipulations, the second is directives with templates which should not manipulate DOM. After components were added, we did not more than changed names.

So Component is nothing more than simple directive which was created as new entity which:

  1. Always has template
  2. Scope is always isolated
  3. Restrict is always Element

I think you can find even more answers in angular sources, but I advise you do not mix these entities, and in case you need to manipulate DOM inside of your component, just use directive inside.


Angular component life cycle hooks allow us to do DOM manipulation inside component controller using $element service

var myApp = angular.module('myApp');
myApp.controller('mySelectionCtrl', ['$scope','$element', MySelectionCtrl]);

myApp.component('mySection', {
    controller: 'mySelectionCtrl',
    controllerAs: 'vm',
    templateUrl:'./component/view/section.html',
    transclude : true
});

function MySelectionCtrl($scope, $element) {
    this.$postLink = function () {
        //add event listener to an element
        $element.on('click', cb);
        $element.on('keypress', cb);

        //also we can apply jqLite dom manipulation operation on element
        angular.forEach($element.find('div'), function(elem){console.log(elem)})

    };

    function cb(event) {
        console.log('Call back fn',event.target);
    }
}

declare component in html

<my-section>
<div class="div1">
    div 1
    <div>
        div 1.1
    </div>
</div>
<div class="div2">
    div 1
</div>

component's partial template(./component/view/section.html)

<div>
<div class="section-class1">
    div section 1
    <div>
        div section 1.1
    </div>
</div>
<div class="section-class1">
    div section 1
</div>