这是一个 TypeScript 示例,说明如何从嵌入式指令回调控制器上的方法。需要注意的最重要的一点是,回调的指令参数名称在定义时使用 &,并且在调用该回调时,您不应使用位置参数,而应使用具有目标中参数名称的属性的对象。
在创建应用模块时注册指令:
module MyApp {
var app: angular.IModule = angular.module("MyApp");
MyApp.Directives.FileUploader.register(app);
}
注册码如下:
module MyApp.Directives.FileUploader {
class FileUploaderDirective implements angular.IDirective {
public restrict: string = "E";
public templateUrl: string = "/app/Directives/FileUploader/FileUploaderDirective.html";
//IMPORTANT - Use & to identify this as a method reference
public scope: any = {
onFileItemClicked: "&"
};
public controller: string = "MyApp.Directives.FileUploader.Controller";
public controllerAs: string = "controller";
public bindToController: boolean = true;
public transclude: boolean = true;
public replace: boolean = true;
}
export function register(app: angular.IModule) {
app.controller("MyApp.Directives.FileUploader.Controller", Controller);
app.directive("fileUploader", () => new FileUploaderDirective());
}
}
指令的控制器看起来像这样
module MyApp.Directives.FileUploader {
export class Controller {
public files: string[] = ["One", "Two", "Three"];
//The callback specified in the view that created this directive instance
public onFileItemClicked: (fileItem) => void;
// This is the controller method called from its HTML's ng-click
public fileItemClicked(fileItem) {
//IMPORTANT: Don't use comma separated parameters,
//instead use an object with property names to act as named parameters
this.onFileItemClicked({
fileItem: fileItem
});
}
}
}
指令的 HTML 看起来像这样
<ul>
<li ng-repeat="item in controller.files" ng-click="controller.fileItemClicked (item)">
{{ item }}
</li>
</ul>
主视图将具有您的指令的实例,如下所示
<body ng-app="MyApp" ng-controller="MainController as controller">
<file-uploader on-file-item-clicked="controller.fileItemClicked(fileItem)"/>
</body>
现在你的 MainController 上只需要一个方法
public fileItemClicked(fileItem) {
alert("Clicked " + fileItem);
}