2014-10-28 6 views
0

일부 지시문은 매우 유사하지만 다른 지시문은 매우 다릅니다. 중복 코드 상속의 양을 줄이기 위해, 그러나 아직 지시어 클래스를 인스턴스화하는 방법을 알지 못했습니다.Typescript 클래스로 구현 된 AngularJs 지시문 등록

/// <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); }); 


} 

I 나타나는 오류는 다음과 같습니다 : TypeError: Cannot read property '$window' of undefined

답변

2

나는이 모습 this 대답에 javasript.Take 내에서 변수의 범위가 문제가 될 수 있다고 생각 여기

내가 tryed 한 것입니다 . 아래에 설명 된 답변이 포함되어 있으며 아주 좋은 설명이 있습니다.

link 메서드의 this 포인터가 예상대로 설정되지 않았습니다. 그냥 람다 함수로 링크 함수를 구현하려고하므로 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

+0

예,이 비디오는 정말 좋았습니다. 인터셉터와 동일한 문제가있었습니다 ... – boindiil

+1

완전성을 위해 : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1 – CodeTower