Typescript + Angular

Typescript + Angular

本文关键字:Angular Typescript      更新时间:2023-09-26

我正在使用带有Angular的Typescript,如下所述http://www.youtube.com/watch?v=WdtVn_8K17E

class MyController {
    thescope: any;
    static $inject = ['$scope'];
    constructor($scope) {
        $scope.vm = this;
        this.thescope = $scope;
    }
    ...
}

我想创建这个控制器的一个实例。我必须使用什么作为$scope参数?

var mc = new MyController(whatParameterHere?); // 

如果您正在寻找在控制器和或指令之间调用的通用方法,请使用服务。

如果您希望操作dom,请使用指令。

回答您的问题:

module myApp.ctrl {
    myApp.controller("MyController", function($scope) {
        return new MyController($scope);
    }
    class MyController {
        thescope: any;
        static $inject = ['$scope'];
        constructor($scope) {
            $scope.vm = this;
            this.thescope = $scope;
        }
        ...
    }
}

您应该使用服务而不是控制器

服务,您可以将其注入并在应用程序中调用其函数。

例如,如果您想从api调用数据:

module Data {
    export interface IDataService {
        http:ng.IHttpService;
        fetch:()=>ng.IPromise<string>;
    }
    export class DataService implements IDataService{
        http:ng.IHttpService;
        static $inject = ["$http"];
        constructor($http:ng.IHttpService) {
            this.http = $http;
        }
        fetch():ng.IPromise<string> {
            return this.http.get("link");
        }
    }
}
angular.module("app").service("DataService", Data.DataService);

如果你想使用像jstree这样的插件,你应该为它创建一个指令,并在其中注入DataService,然后使用你想要的函数。

在AngularJS中,您的dom操作应该按照指令进行。在您的案例中,您将为JSTree创建一个指令。这个答案应该会让你领先一步:如何将jsTree事件与AngularJS 一起使用

要了解更多关于指令的信息,这里有一个来自AngularJS创作者的精彩视频:https://www.youtube.com/watch?v=WqmeI5fZcho(我会在某个时候制作AngularJS+TypeScript指令视频)

正如其他人所建议的,你不应该自己做这件事,angular会自己做的。

但它可以通过将$scope作为字符串传递来完成,angular将为您执行DI,所以您的代码应该看起来像这个

var mc = new MyController("$scope"); 

通常,您会使用一个声明为参数的私有变量来保存注入的$scope对象,如下所示:

..
class MyController {
  
  static $inject = ['$scope'];
  constructor(private scope: ng.IScope){
    this.init();  
  }
  
  private init() {
    this.scope.foo = 'bar';
  }
  
}
..

虽然$inject语句不是必不可少的,但它明确指出$scope是一种注入的资产:-)

然后,您将以角度方式创建MyController的实例,如下所示:

angular.module('app')
  .controller('MyController', MyController);