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:
- A Controller class
- Component declaration
- Initialization
- 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>{{ctrl.thing.id}}</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
Initialization
angular.module('module_name').component(ControllerClass.SELECTOR, component);
Usage
Passing a variable
<my-directive obj="some variable"></my-directive>
Passing a string
<my-directive obj="'this is my string'"></my-directive>
Bindings
Symbol | Binding |
---|---|
< | one-way |
= | two-way |
& | function binding |
@ | strings only |