2

I am using a combination of Angularjs + Typescript for my project. I am searching for a good code convention. There are some some good examples for the two technologies separately. For example I follow this one when using TypeScript:

https://github.com/Platypi/style_typescript#introduction

But couldn't find a good one for the combination of Angularjs + Typescript. To be a little bit more specific, for example, I need a convention on how to write directives with the typescript syntax etc.

I could not find any good articles on the topic. If someone can share something on the topic it will be great. Thanks!

1

2 Answers 2

1

I have followed this projects structure when writing angularjs + typescript.

Since directives are actually factory functions writing directives will be done in the same way:

module Directives{
  export function MyDirective(optionalService): ng.IDirective{
     var myDirective = {};
     myDirective.restrict = 'A';
     myDirective.link = function(scope, elem){};
     //etc
     return myDirective;
  }
  MyDirective.$inject = ["optionalService"];
}

app.directive("myDirective", Directives.MyDirective);
Sign up to request clarification or add additional context in comments.

Comments

0

If you use Angular1.5+ you can follow Angular2 Component style:

class DemoController implements ng.IComponentController {
    public static $inject = [
        'Service1',
    ];
    constructor(private Service1: IService1) {
        //
    }

    public $onInit(): void {
        // ---
    }

    public $postLink(): void {
        // ---
    }

    // ---
}

export const DemoComponent = {
    selector: 'demoComponent',
    bindings: {
        prop1: '<',
        prop2: '<',
    },
    controller: DemoController,
    templateUrl: require('./your-tpl.html'),
};

And somewhere in your module, you can register this component:

.component(DemoComponent.selector, DemoComponent)

For creating directives this code style is also pretty nice:

export class MyDemoDirective implements ng.IDirective {
    public restrict: string;

    public static $inject: string[] = [
        'Service1',
        'Service2',
    ];

    constructor(private Service1: IService1, private Service2: IService2) {
        this.restrict = 'A';
        // ---
    }

    public link(...) {
        // ---
    }

    public static factory(): ng.IDirectiveFactory {
        const directive = (Service1: IService1, Service2: IService2) => {
            return new MyDemoDirective($filter, User);
        };
        return directive;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.