【发布时间】:2018-01-09 10:49:15
【问题描述】:
我正在使用 TypeScript 中的 Angular 1.5 编写一个应用程序。我有一个组件应该在调整窗口大小时更改视图的模板。 (因为我有一个移动模板和一个桌面模板)
当它用纯 Javascript 编写时,它曾经可以正常工作。现在它在 Typescript 中,我在定义函数时遇到了问题,因为我是 TypeScript 的新手,我看不出问题出在哪里。
在 Javascript 中,组件是一个指令,看起来像这样:
angular.module('app.directives').directive('adaptScreen', adaptScreen);
adaptScreen.$inject = ['$window', '$state'];
function adaptScreen($window, $state) {
return {
restrict: 'E',
template: '<div ng-include="templateUrl"></div>',
link: function (scope) {
var rootUrl = 'public/app/views/';
$window.onresize = function () {
changeTemplate();
scope.$apply();
};
changeTemplate();
function changeTemplate() {
var screenWidth = $window.innerWidth;
if (screenWidth < 1050) {
scope.templateUrl = rootUrl + $state.current.name + '-mobile.html';
} else if (screenWidth >= 1050) {
scope.templateUrl = rootUrl + $state.current.name+'-desktop.html';
}
}
}
}
};
在我的 home.html 视图中,我有:
<adapt-screen></adapt-screen>
它过去工作得很好。
现在,在 TypeScript 中,组件看起来像这样:
const rootUrl = 'public/app/views/';
let templateUrl = '';
class AdaptViewComponentController implements IAdaptViewComponentController {
static $inject = ['$window', '$state','$scope'];
constructor($window: Window, $state: ng.ui.IStateService, $scope: ng.IScope) {
$window.onresize = function () {
this.changeTemplate($window,$state,$scope);
$scope.$apply;
}
//console.log('in');
};
private changeTemplate($window: Window, $state: ng.ui.IStateService, $scope: ng.IScope):void {
let screenWidth = $window.innerWidth;
console.log('in');
if (screenWidth < 1050) {
templateUrl = rootUrl + $state.current.name + '/'+ $state.current.name + '-mobile.html';
} else if (screenWidth >= 1050) {
templateUrl = rootUrl + $state.current.name + '/' + $state.current.name + '-desktop.html';
}
console.log('change' + templateUrl);
};
}
class AdaptViewComponent implements ng.IComponentOptions {
public bindings: any;
public controller: any;
public controllerAs: string;
public templateUrl: string;
constructor() {
this.bindings = {};
this.controller = AdaptViewComponentController;
this.controllerAs = 'AdaptView';
this.templateUrl = templateUrl;
console.log(this.templateUrl);
}
}
angular.module('rundeckManager.adapt')
.component('adaptView', new AdaptViewComponent());
因为我更改了组件的名称,所以 home.html 现在有了这个:
<adapt-view></adapt-view>
如您所见,console.log 有很多,因为我不太了解正在发生的事情。但是在这里我渲染了一个空白页面,因为 templateUrl 是空的,因为应用程序无法调用函数'changeTemplate($window,$state,$scope)',我在屏幕调整大小时收到以下错误:
Uncaught TypeError: this.changeTemplate is not a function
at AdaptViewComponentController.$window.onresize
打字稿编译器没有显示任何问题,但在执行时我的函数无法识别。我不知道为什么,任何帮助将不胜感激。
【问题讨论】:
-
你需要将
this从构造函数传递给onresize回调
标签: angularjs typescript angularjs-directive typeerror