Roadmap › AngularJS (1.x) — Legacy › Module: Scope, Digest and Directives
Lessons in this course (13)

10. Custom directives and components

Advanced★ Must knowLesson 10 of 13
js
// Component (1.5+) — preferred: isolated scope, controller-as, lifecycle hooks
app.component("orderCard", {
  bindings: { order: "<", onSelect: "&" },           // < one-way, @ string, & callback, = two-way (avoid)
  template: `
    <div class="card" ng-click="$ctrl.onSelect({ id: $ctrl.order.id })">
      #{{ $ctrl.order.id }} — {{ $ctrl.order.total | currency }}
    </div>`,
  controller: function () {
    this.$onInit = () => { /* init */ };
    this.$onChanges = changes => { if (changes.order) { /* react */ } };
    this.$onDestroy = () => { /* cleanup */ };
  },
});
// <order-card order="o" on-select="vm.open(id)"></order-card>

// Directive — for DOM manipulation / attribute behaviour
app.directive("autoFocus", ["$timeout", function ($timeout) {
  return {
    restrict: "A",                                    // E element, A attribute, C class, M comment
    link(scope, element) { $timeout(() => element[0].focus()); },
  };
}]);

Scope options for directives: scope: false (share parent), scope: true (child scope, prototypal inheritance), scope: {} (isolated). transclude: true lets a directive wrap content (<ng-transclude>). require accesses other directive controllers (e.g. ngModel).