鑑於這段代碼:爲什麼'this'在此TypeScript片段中引用'window'?
module movieApp {
export interface IHomeControllerScope extends ng.IScope {
moviesToDownload: string[];
active: string;
deleteMovieFromDownloadList(movie: any);
markMovieAsDownloaded(movie: any);
}
export class HomeController {
public static $inject = [
'$scope',
'$location',
'MovieService'
];
constructor(private $scope: IHomeControllerScope, private $location: ng.ILocationService, private MovieService) {
this.$scope.$on('$locationChangeSuccess', (event) => {
this.setActiveUrlPart();
});
MovieService.getMoviesToDownload().then(response => {
this.$scope.moviesToDownload = response;
});
}
private setActiveUrlPart() {
var parts = this.$location.path().split('/');
this.$scope.active = parts[1];
}
public get moviesToDownload() {
return this.$scope.moviesToDownload;
}
public markMovieAsDownloaded(movie: any) {
movie.Downloaded = true;
}
public deleteMovieFromDownloadList(movie: any) {
this.MovieService.deleteMovieFromDownloadList(movie).then(() => {
debugger;
this.$scope.moviesToDownload = _.without(this.$scope.moviesToDownload, movie);
});
}
}
}
app.controller("HomeController", movieApp.HomeController);
一切都運行得很好,但在線路this.$scope.moviesToDownload = _.without(this.$scope.moviesToDownload, movie);
的方法deleteMovieFromDownloadList
,this
指的不是實際的對象我預計到窗口對象。
生成的JavaScript看起來像這樣:
正如你所看到的,所產生的JS,具體方法使用_this。這看起來不錯,對吧?
有人可以向我解釋發生了什麼,以及如何解決這個問題?
編輯:
我已經使用這個與角度:
<body data-ng-app="movieApp" data-ng-controller="HomeController as homeCtrl">
<div class="col-sm-1">
<i class="fa fa-trash-o" data-ng-click="homeCtrl.deleteMovieFromDownloadList(m)" title="Verwijder uit lijst"></i>
</div>
</body>
編輯II: 嘗試所有的建議,然後設置回原來的代碼我已經張貼在這裏,一切之後只是工作正常!我不知道如何,但我想這與Chrome/VS 2013有關。無論如何,感謝那些試圖幫助我的人。
可能「deleteMovie ...」函數綁定到按鈕或其他UI元素。在這種情況下,該功能在窗口上下文中執行。要解決該問題,您應該在控制器的構造函數中定義函數體:this.deleteMovieFromDownloadList =(movie:any)=> this.MovieService.deleteMovieFromDownloadList(movie).then(()=> { debugger; this。$ scope.moviesToDownload = _.without(this。$ scope.moviesToDownload,movie); }); } – TSV
我總是在構造函數中移動這樣的函數。我確定這是在TypeScript控制器中用「this」解決問題的最簡單方法。 – TSV