2014-10-28 42 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