我已经添加了AngularJS定义。目前我的app控制器看起来像这样:
app.controller('appController',
[
'$scope',
'$state',
'utilityService',
appController
]);
function appController(
$scope: ng.IScope,
$state,
utilityService
) {
var app = this;
$scope.broadcast = function (val) {
$scope.$broadcast('broadcast', val);
};
if (app.auth.user.isAuthenticated()) {
app.state.text = null;
$state.transitionTo('home.content', { content: 'overview' });
} else {
$state.transitionTo('authentication');
// app.auth.loginData = app.cache.get('loginData');
app.state.text = "Please Login ...";
}
}
如果我想充分利用TS,我是否应该转换为类?如果是这样,我如何处理广播函数等函数的定义?
答案 0 :(得分:5)
这是原则
app.controller('appController', AppController);
interface AppControllerScope extends ng.IScope{
vm: AppController;
}
class AppController{
text: string;
static $inject=[
'$scope',
'$state',
'utilityService'
]
constructor(
public $scope: AppControllerScope,
public $state,
public utilityService: UtilityService
) {
$scope.vm = this;
// NOTE: unclear what app is, perhaps its a service?
if (app.auth.user.isAuthenticated()) {
this.text = null;
$state.transitionTo('home.content', { content: 'overview' });
} else {
$state.transitionTo('authentication');
// app.auth.loginData = app.cache.get('loginData');
this.text = "Please Login ...";
}
}
broadcast = (val) => {
this.$scope.$broadcast('broadcast', val);
};
}
要点:
vm.something
从视图中访问控制器功能,例如ng-click="vm.broadcast('tada')"
utilityService
是UtilityService
的一个实例,您可以获得类型安全性。更多:https://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1 更多使用类作为控制器模式:https://www.youtube.com/watch?v=WdtVn_8K17E&hd=1
答案 1 :(得分:0)
这是我的工作方式
module protal{
var app =angular.module('portal',[]);
app.controller(controllers)
}
module portal.controllers{
// register any no of controllers here in this namespace
export class masterController{
public fooFunc(){
}
static $inject=['$scope'];
constructor($scope){
$scope.vm=this;
}
}
}