在$ scope和$ mdDialog是静态的情况下,以下工作。
declare var module: any;
export interface IChangePassword extends ng.IScope {
cancel: Function;
myname: string;
state: string;
processRequest: Function;
CurrentPassword: string;
NewPassword: string;
ConfirmPassword: string;
}
export class ChangePasswordController {
static $inject = ["$scope", "$mdDialog","$timeout"];
static $mdDialog: any;
static $timeout: any;
state: string = 'getInput';
static $scope: IChangePassword;
CurrentPassword: string;
NewPassword: string;
ConfirmPassword: string;
ChangePasswordService: any;
constructor($scope: IChangePassword, $mdDialog: any, $timeout: any) {
ChangePasswordController.$mdDialog = $mdDialog;
ChangePasswordController.$scope = $scope;
$scope.state = this.state;
$scope.cancel = this.cancel;
$scope.processRequest = this.processRequest;
//this.ChangePasswordService = ChangePasswordService;
ChangePasswordController.$timeout = $timeout;
}
public cancel ():void {
ChangePasswordController.$mdDialog.cancel();
};
public processRequest(): void {
ChangePasswordController.$scope.state = 'processRequest';
ChangePasswordController.$timeout(function () {
ChangePasswordController.$scope.state = 'Done';
}, 5000);
}
}
module.exports = function (app) {
app.controller("ChangePasswordController", ChangePasswordController);
}
以下无效。在processRequest()中,对象this。$ scope始终为null。请帮忙。
export class ChangePasswordController {
static $inject = ["$scope", "$mdDialog","$timeout"];
static $mdDialog: any;
static $timeout: any;
state: string = 'getInput';
$scope: IChangePassword;
CurrentPassword: string;
NewPassword: string;
ConfirmPassword: string;
ChangePasswordService: any;
//myname: string = 'gaurav';
constructor($scope: IChangePassword, $mdDialog: any, $timeout: any) {
ChangePasswordController.$mdDialog = $mdDialog;
this.$scope = $scope;
$scope.state = this.state;
$scope.cancel = this.cancel;
$scope.processRequest = this.processRequest;
//this.ChangePasswordService = ChangePasswordService;
ChangePasswordController.$timeout = $timeout;
}
public cancel ():void {
ChangePasswordController.$mdDialog.cancel();
};
public processRequest(): void {
this.$scope.state = 'processRequest';
ChangePasswordController.$timeout(function () {
this.state = 'Done';
}, 5000);
}
}
module.exports = function (app) {
app.controller("ChangePasswordController", ChangePasswordController);
}
我不确定为什么$ scope无法用作实例变量。在这段代码中。请让我知道是否有编写此代码的更好方法。
谢谢
问题是您传递processRequest
给该函数时$scope
未绑定当前对象this
。在Javascript中,this
由调用者确定,而不由声明上下文确定。您可以使用bind
将当前对象绑定到函数,或者使用this
从声明上下文捕获的箭头函数:
$scope.processRequest = this.processRequest.bind(this);
$scope.processRequest = () => this.processRequest();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句