我有几个指令在某些方面非常相似,但在其他指令上却截然不同。为了减少重复代码继承的数量,可以使用,但是我还没有想出如何实例化一个指令Class。
以下是我的尝试:
/// <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
答案 0 :(得分:2)
我认为这可能是javasript中变量范围的问题。看看this答案。这包含下面描述的答案,并有一个非常好的解释。
问题是,方法this
中的link
指针未按预期设置。只是尝试将链接函数实现为lambda函数,因此typescript负责正确设置this指针。
只需比较以下结果:
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;
});