我决定在 TypeScript 中添加另一个描述如何创建和使用控制器的详细信息并将其注入 angularJS 的答案。
这是此答案的扩展
How can I define my controller using TypeScript?我们也有a working plunker
所以有这个指令:
export class CustomerSearchDirective implements ng.IDirective
{
public restrict: string = "E";
public replace: boolean = true;
public template: string = "<div>" +
"<input ng-model=\"SearchedValue\" />" +
"<button ng-click=\"Ctrl.Search()\" >Search</button>" +
"<p> for searched value <b>{{SearchedValue}}</b> " +
" we found: <i>{{FoundResult}}</i></p>" +
"</div>";
public controller: string = 'CustomerSearchCtrl';
public controllerAs: string = 'Ctrl';
public scope = {};
}
我们可以看到,我们声明这个指令可以作为 E 元素使用。我们还嵌入了一个模板。此模板已准备好绑定 SearchedValue 并在我们的控制器 Ctrl.Search() 上调用 Action。我们说控制器的名称是什么:'CustomerSearchCtrl' 并要求运行时将其作为 'Ctrl' (conrollerAs:)
最后我们将该对象注入到 Angular 模块中:
app.directive("customerSearch", [() => new CustomerSearch.CustomerSearchDirective()]);
我们可以将$scope 用作ng.IScope,但要对它进行更多类型的访问,我们可以创建自己的接口:
export interface ICustomerSearchScope extends ng.IScope
{
SearchedValue: string;
FoundResult: string;
Ctrl: CustomerSearchCtrl;
}
这样,我们知道,我们有字符串SearchedValue 和其他字符串FoundResult。我们还通知应用程序,Ctrl 将被注入该范围,并且类型为CustomerSearchCtrl。控制器来了:
export class CustomerSearchCtrl
{
static $inject = ["$scope", "$http"];
constructor(protected $scope: CustomerSearch.ICustomerSearchScope,
protected $http: ng.IHttpService)
{
// todo
}
public Search(): void
{
this.$http
.get("data.json")
.then((response: ng.IHttpPromiseCallbackArg<any>) =>
{
var data = response.data;
this.$scope.FoundResult = data[this.$scope.SearchedValue]
|| data["Default"];
});
}
}
将其注册到模块中
app.controller('CustomerSearchCtrl', CustomerSearch.CustomerSearchCtrl);
这个控制器有什么有趣的地方?它有一个公共行为搜索,可以通过this. 访问其所有成员,例如this.$http。因为我们在 VS 中指示了 angular.d.ts 类型/接口的智能感知
protected $http: ng.IHttpService
将被使用,我们稍后可以轻松访问它的方法。类似的是.then()中返回值的类型
.then((response: ng.IHttpPromiseCallbackArg<any>) => {...
其中确实包含数据:任何类型的 {}...
希望对您有所帮助,请注意action here中的所有内容