如何将我的javascript AngularJS app控制器转换为使用Typescript?

时间:2014-07-26 06:35:29

标签: angularjs typescript

我已经添加了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,我是否应该转换为类?如果是这样,我如何处理广播函数等函数的定义?

2 个答案:

答案 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')"
  • 还使用服务类,例如utilityServiceUtilityService的一个实例,您可以获得类型安全性。更多: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;
    }

  }
}