在下面的Controller中,永远不会调用$ onInit()。请告诉我如何确保调用$ onInit。我需要为此控制器绑定$ onInit。
我是否需要将$ onInit绑定到此对象,而不是将其作为类级别函数。
import * as angular from "angular";
import { IChangePasswordService } from '../../partials/ChangePassword/IChangePasswordService'
declare var module: any;
declare var require: any;
export interface IEmailChangePassword extends ng.IScope {
initialPasswordChange: Function;
}
export class EmailChangePasswordController implements ng.IOnInit {
static $inject = ["$scope", "$mdDialog", "$timeout", "$location", "$state", "ChangePasswordService","common.svcs.modalService"];
$mdDialog: any;
$timeout: any;
state: string = 'getInput';
$scope: IEmailChangePassword;
modalService: any;
ChangePasswordService: IChangePasswordService;
$location: ng.ILocationService;
$state: any;
constructor($scope: IEmailChangePassword, $mdDialog: any, $timeout: any, $location: ng.ILocationService, $state: any, ChangePasswordService: IChangePasswordService, modalService:any) {
this.$mdDialog = $mdDialog;
this.$scope = $scope;
$scope.initialPasswordChange = this.initialPasswordChange.bind(this);
this.$timeout = $timeout;
this.modalService = modalService;
this.ChangePasswordService = ChangePasswordService;
this.$location = $location;
this.$state=$state;
}
$onInit(): void {
console.log("inside On Init");
}
public initialPasswordChange(): void {
...
}
}
module.exports = function (app) {
app.controller("EmailChangePasswordController", EmailChangePasswordController);
}
我在这里使用带有angularjs的Typescript。非常感谢你提前。
答案 0 :(得分:4)
$ onInit是AngularJS中组件生命周期的钩子。
https://docs.angularjs.org/guide/component
当您将此控制器分配给组件并使用时,它将触发 这个组件在某处。
你应该有类似的组件:
export class EmailChangePasswordComponent {
controller = EmailChangePasswordController;
templateUrl = "email-change-password.html";
}
您应该注册:
app.component("emailChangePassword", EmailChangePasswordComponent)
您可以在配置中将此组件指定为状态:
$stateProvider.state("stateName", {
url: "/stateUrl",
component: "emailChangePassword"
});
或者只是在html中使用:
<email-change-password></email-change-password>
当初始化状态或正在渲染组件时,$ onInit将触发。
构造函数和 $ onInit 之间的区别在于$ onInit仅在构造Element时触发(您可以通过$元素操作DOM元素)以及所有绑定(输入)到组件)已初始化。