AngularJS TypeScript directive link function -
i'm trying create angularjs directive using typescript. directive requires 'ngmodel' , i'm using custom service injected in directive. main problem service can't used inside link function.
here example of i'm trying achieve:
module app.directives { export var directivename: string = "thedirective"; angular.module("myapp").directive(directivename, (myfactory: app.services.myfactory) => { return new mydirective(myfactory); }); export interface imydirectivescope extends ng.iscope { ngmodel: ng.ingmodelcontroller; } export class mydirective implements ng.idirective { restrict = "a"; require = "ngmodel"; scope = { ngmodel:'=' } constructor(private myfactory: app.services.myfactory) { } link(scope: imydirectivescope , elem: jquery, attributes: ng.iattributes, ngmodel: ng.ingmodelcontroller) { //this window here elem.bind('blur', (evt: jqueryeventobject) => { //keyword window here, yeah bummer indeed validate(); }); function validate() { //i need use factory here, can seem it. //this window , i'm kinda stuck here } } } }
i can't seem find more advanced stuff on topic. examples don't find don't seem uses services or complex link function. please answer question sort of example. it's trickery think.
update: fact 'this' inside link function window , not 'mydirective' doesn't make sense me. ideas why be?
classes work great controllers , directive controllers don't think i'd use 1 whole directive. if want you'd have this:
export class mydirective implements ng.idirective { public link; restrict = "a"; require = "ngmodel"; scope = { ngmodel:'=' } constructor(private myfactory: app.services.myfactory) { this.link = this.unboundlink.bind(this); } unboundlink(scope: imydirectivescope , elem: jquery, attributes: ng.iattributes, ngmodel: ng.ingmodelcontroller) { //now should able access myfactory this.myfactory.dosomething(); elem.bind('blur', (evt: jqueryeventobject) => { //keyword window here, yeah bummer indeed validate(); }); function validate() { //i need use factory here, can seem it. //this window , i'm kinda stuck here } } }
edit: without class this:
angular.module("myapp").directive("thedirective", function(myfactory: app.services.myfactory) { return { restrict: 'a', require: 'ngmodel', scope: {'ngmodel': '='}, link: function(scope: imydirectivescope , elem: jquery, attributes: ng.iattributes, ngmodel: ng.ingmodelcontroller) { //you can access myfactory this. myfactory.dosomething(); } } } );
Comments
Post a Comment