2014-10-28 17 views
0

我有几个指令在某些方面非常相似,但在其他方面却非常不同。为了减少重复代码继承的数量可以使用,但是我还没有想出如何实例化一个指令类。注册AngularJs指令作为Typescript类实现

以下是我已经tryed:

/// <reference path='../_all.ts' /> 

module app.directives { 
    'use strict'; 

    export class myDirective implements ng.IDirective 
    { 

    private margin = {top: 70, right: 20, bottom: 40, left: 55}; 
    private padding = {top: 10, right: 10, bottom: 10, left: 10}; 

    public restrict = 'A'; 
    public $scope = { 
     regulationdata: "=", 
     title: "=" 
    }; 

    constructor(private $window) {} 

    public link($scope, element: JQuery, attr: ng.IAttributes) 
    { 

     // Browser onresize event 
     this.$window.onresize = function() { // TypeError: Cannot read property '$window' of undefined 
     $scope.$apply(); 
     }; 

     // lots of application specific code. 
    } 
    } 
    /** Register directive */ 
    angular.module('app').directive('myDirective',['$window', ($window) => { return new myDirective($window); }); 


} 

我收到的错误是:TypeError: Cannot read property '$window' of undefined

回答

2

我认为这可能看看this答案与内javasript.Take变量的作用域问题。这包含下面描述的答案,并有一个非常好的解释。

问题是,方法link中的this指针未按预期设置。只要尝试将链接函数作为lambda函数来实现,那么typescript会正确地设置这个指针。

只是相比较,结果如下:

export class Test { 
    private property: string; 
    public link() { 
     this.property; 
    } 
} 

export class Test2 { 
    private property: string; 
    public link =() => { 
     this.property; 
    } 
} 
define(["require", "exports"], function(require, exports) { 
    var Test = (function() { 
     function Test() { 
     } 
     Test.prototype.link = function() { 
      this.property; 
     }; 
     return Test; 
    })(); 
    exports.Test = Test; 

    var Test2 = (function() { 
     function Test2() { 
      var _this = this; 
      this.link = function() { 
       _this.property; 
      }; 
     } 
     return Test2; 
    })(); 
    exports.Test2 = Test2; 
}); 
+0

感谢,从链接的视频,您添加,才是真的好解释的问题。 – CodeTower 2014-10-28 13:49:31

+0

是的,这个视频真的很好,我有拦截器的问题... – boindiil 2014-10-28 13:55:26

+1

为了完整性:https://www.youtube.com/watch?v=tvocUcbCupA&hd=1 – CodeTower 2014-10-28 14:30:27