Typescript + Angular
Typescript + Angular
我正在使用带有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);
- Angular 2.0 with JavaScript or TypeScript?
- Typescript编译器错误,Angular 1.5组件应为分号
- 将typescript函数访问到angular中
- 在新路由器上使用订阅函数时出现Angular 2 typescript错误(rc 1)
- Angular 2中的@Angular包缺少TypeScript类型定义
- 让typescript与facebook登录为Angular 2项目工作
- 将ng2图表添加到Typescript/ Angular 2项目引用路径和.js文件的路径不正确
- 我只能将TypeScript用于Angular应用程序的部分吗
- 在Typescript中对array/JONS进行迭代,以构建带有子菜单的Angular 2模板菜单
- 使用由angular指令中的typescript生成的控制器
- 无法使用typescript访问angular中另一个控制器中声明的$rootscope属性
- angular 2和谷歌地图api的typescript逻辑问题
- 如何将Electron ipcRenderer集成到基于TypeScript的Angular 2应用程序中
- Typescript+Angular公开服务方法
- 在 Angular 2 / TypeScript 中使用数据输入的 pdfMake
- Typescript async/await and angular $q service
- Angular+TypeScript+外部模块.如何跨文件维护类型信息
- Angular TypeScript service this is undefined
- Angular/Typescript——从例子中解释接口的好处
- Angular + Typescript:在控制器类中使用指令类作用域变量