How to use Component/Directive's in AngularJS

Here is a easy way to create a component or directive in AngularJS. This is an AngularJS Essential!

Parts you need to complete the component/directive:

  1. A Controller class
  2. Component declaration
  3. Initialization
  4. Usage Example

Controller class

On the class you should have

    interface Thing {
        id: number;

    class ControllerClass {
        public static readonly SELECTOR = 'myDirective';
        public static readonly CONTROLLER_AS = 'ctrl';

        public obj: Thing;

        public $onInit() {
            if(this.obj === undefined) { // check the object is set
                console.log('you need to set the obj')

Component Declaration

const component = {
    template: '<div>{{}}</div>',
    controller: ControllerClass,
    controllerAs: ControllerClass.CONTROLLER_AS,
    bindings: {
        thing: '=' // see bindings below for more information

Note: Be careful of a few gotcha's regarding the capitalization of controllerAs


angular.module('module_name').component(ControllerClass.SELECTOR, component);


Passing a variable

<my-directive obj="some variable"></my-directive>

Passing a string

<my-directive obj="'this is my string'"></my-directive>


Symbol Binding
< one-way
= two-way
& function binding
@ strings only