jose luis garcia cespedes jose luis garcia cespedes - 1 month ago 18
AngularJS Question

Directive to Component Angular 1.5x

I have to spend several directives components.
But the truth I do not quite ented changes.
It can be done for example with the directive below, in such a case. As?
Thank you very much.

(function() {
'use strict';

angular
.module('01')
.directive('tableSortable', tableSortable);

/** @ngInject */
function tableSortable() {
return {
restrict: 'E',
transclude: true,
templateUrl: 'app/components/tabla/tableSortable.html',
scope: {
columns: '=',
data: '=',
sort: '=',
click: '&'
},
link: function(scope) {
scope.selectedClass = function(columnName) {
return columnName == scope.sort.column ? 'sort-' + scope.sort.descending : false;
};
}
};


}
})();

Answer

A simple explanation about what is component and it's relation with directive was given in the docs.

In Angular, a Component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure, (AngularJs guide for components).

Basically, a component is a simple directive with a default behaviour defined for link and compile phase and also other deep behaviours like priority or restrict for example. Also, the scope is always isolated on a component, because all the interaction between scopes must be controlled by the component's bindings.

A component is destinated to create reusable interface blocks without focusing much on the elements deep behaviour but on the feature of that block, it's like a more objective directive not behavioral. Anyways, component-like directives have already been used before, but it just wasn't called component yet.

In relation to a directive declaration, a component doesn't change much, it become a little simpler to declare directives like that but it has most of the directives features. Your directive for example, would look like the code bellow.

(function() {
  'use strict';

  angular
    .module('01')
    .component('tableSortable', {
      transclude: true,
      templateUrl: 'app/components/tabla/tableSortable.html',
      controller: TableSortableComponentController,
      controllerAs: '$ctrl',
      bindings: {
        // consider using a one-way binding like '>'
        columns: '=',
        data: '=',
        sort: '=',
        click: '&'
      }
    });

  function TableSortableComponentController($scope, $element, $attrs) {
    var $ctrl = this;

    $ctrl.selectedClass = function(columnName) {
      return columnName == $ctrl.sort.column ? 'sort-' + $ctrl.sort.descending : false;
    };
  }    
})();