angular-ts-decorators
angular-ts-decorators copied to clipboard
@Directive examples
I just started using this library a few days ago and it's great! I'm trying to migrate my code base over and everything's going pretty smoothly except for @Directives. Are there any examples around showing how to use @Directive? I'm trying to move my link/compile methods to @Directive-decorated class controllers, but don't really understand how to get access to $scope/$element/$attributes injected into the new class constructor. Any help would be great!
Agreed that this is a glaring omission from the docs. Directive will be very similar to component. Most often you'll probably only need to supply a selector and maybe a require. Like the component, avoid $scope. You can inject $element and $attrs.
If you're following the Angular 2+ style, you'll want to avoid compile as much as possible. It just doesn't translate. This is probably what makes migrating directives the most challenging. You may have to rethink the architecture. Sometimes it may even be easier to start fresh.
Thanks! The $element and $attrs was the tricky part. I was able to update pretty easily after that. A very simple directive I converted ended up looking like this:
import { Directive, Input } from "angular-ts-decorators";
import * as angular from "angular";
import * as _autosize from "autosize";
@Directive({
selector: "[autosize]"
})
export class AutosizeDirective {
private enabled = false;
private initialized = false;
private options = {
enabled: false
};
/*@ngInject*/
constructor(private $scope, private $element, private $parse) {
}
@Input()
set autosize(value) {
const adapter = this.$parse(value)(this.$scope) || {};
// setup options
angular.extend(this.options, adapter.options, {});
// add api methods
angular.extend(adapter, {
enable: this.enable,
update: this.update
});
if (this.options.enabled) {
this.enable(true);
}
}
private initialize() {
if (!this.initialized) {
this.initialized = true;
}
}
private enable(e: any) {
if (e) {
if (!this.enabled) {
this.initialize();
_autosize(this.$element);
}
} else {
if (this.enabled) {
_autosize.destroy(this.$element);
}
}
this.enabled = this.options.enabled = e;
}
private update() {
if (this.enabled) {
_autosize.update(this.$element);
}
}
}