Define AngularJS directive using TypeScript and $inject mechanism -


recently started refactoring 1 of angular projects working on typescript. using typescript classes define controllers convenient , works minified javascript files static $inject array<string> property. , pretty clean code without splitting angular dependencies class definition:

 module app {   'use strict';   export class appctrl {     static $inject: array < string > = ['$scope'];     constructor(private $scope) {       ...     }   }    angular.module('myapp', [])     .controller('appctrl', appctrl); } 

right searching solution handle similar case directive definition. found practice define directives function:

module directives {    export function mydirective(toaster): ng.idirective {     return {       restrict: 'a',       require: ['ngmodel'],       templateurl: 'mydirective.html',       replace: true,       link: (scope: ng.iscope, element: ng.iaugmentedjquery, attrs: ng.iattributes, ctrls) =>          //use of $location service         ...       }     };   }     angular.module('directives', [])     .directive('mydirective', ['toaster', mydirective]); } 

in case forced define angular dependencies in directive definition, can error-prone if definition , typescript class in different files. best way define directive typescript , $inject mechanism, searching way implement typescript idirectivefactory interface not satisfied solutions found.

using classes , inherit ng.idirective way go typescript:

class mydirective implements ng.idirective {     restrict = 'a';     require = 'ngmodel';     templateurl = 'mydirective.html';     replace = true;      constructor(private $location: ng.ilocationservice, private toaster: toasterservice) {     }      link = (scope: ng.iscope, element: ng.iaugmentedjquery, attrs: ng.iattributes, ctrl: any) => {         console.log(this.$location);         console.log(this.toaster);     }      static factory(): ng.idirectivefactory {         const directive = ($location: ng.ilocationservice, toaster: toasterservice) => new mydirective($location, toaster);         directive.$inject = ['$location', 'toaster'];         return directive;     } }  app.directive('mydirective', mydirective.factory()); 

related answer: https://stackoverflow.com/a/29223360/990356


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -