我有两个打字稿控制器
Controller A
{
public methodOfA()
{//do something}
}
Controller B
{
public methodOfB()
{//do something}
}
我怎样才能实现这样的目标
Controller B
{
A.methodOfA();
}
答案 0 :(得分:0)
也许是这样的:
class ControllerA
{
constructor($scope)
{
//do something
}
public static methodOfA()
{
//do something
}
}
class ControllerB
{
constructor($scope)
{
//do something
ControllerA.methodOfA();
}
}
虽然(正如其他人的评论中所述) - 我不推荐这种方法。为此目的使用服务。
答案 1 :(得分:0)
class ControllerA {
static $inject = ['$http', '$scope','app.services.CommonService'];
constructor(
private $http: ng.IHttpService,
private $scope: ng.IScope,
private commonService: app.services.ICommonService){
}
//common method call from controller A
this.commonService.CommonMethod();
}
class ControllerB {
static $inject = ['$http', '$scope','app.services.CommonService'];
constructor(
private $http: ng.IHttpService,
private $scope: ng.IScope,
private commonService: app.services.ICommonService){
}
//common method call from controller B
this.commonService.CommonMethod();
}
module app.services {
//common interface for exposing service
export interface ICommonService {
CommonMethod();
}
export class CommonService implements ICommonService{
static $inject = ['$http'];
constructor(private $http: ng.IHttpService) {
}
public CommonMethod(){
//common method defination here
}
}
factory.$inject = ['$http'];
function factory($http: ng.IHttpService) {
return new CommonService($http);
}
angular.module('yourApp')
.factory('app.services.CommonService', factory);
}
正如Kobi所提到的,我使用了一个commom服务来公开常用方法。