Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Components and directives in angular 1.5

The big feature changes in Angular 1.5 are surrounding the support of components.

component('myComponent', {
  template: '<h1>Hello {{ $ctrl.getFullName() }}</h1>',
  bindings: { firstName: '<', lastName: '<' },
  controller: function() {
    this.getFullName = function() {
      return this.firstName + ' ' + this.lastName;
    };
  }
});

While this is all good, I am not sure how this differs from directives. What are the benefits of using components over traditional custom directives? And are components in Angular 1.5 and Angular 2 the same?

like image 275
sjokkogutten Avatar asked Feb 06 '16 17:02

sjokkogutten


1 Answers

The .component DOES NOT replaces .directive like @rek Żelechowski said. So..

There’s nothing you can do with .component() that you can’t do with .directive(). It aims to simplify the way we create “components” – which roughly means UI directives.

When can/should you use it?

Clearly there are a few cases where you can’t/shouldn’t use it:

  • If you need the link function (though you rarely should)
  • If you want a template-less directive, e.g. ng-click that doesn’t have a template or separate scope

For all your other directives, this should work. And because it saves on boilerplate and less error-prone it’s nicer to use.

Despite of all new goodies, .component() can’t fully replace .directive().

like image 171
Pedro Justo Avatar answered Oct 24 '22 10:10

Pedro Justo