我已经在 ag 网格上创建了 wrapper 指令,如下所示
function MyDirective(): ng.IDirective {
var directive = <ng.IDirective>{
restrict: "E",
template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGridOptions" class="ag-fresh ag-basic"></div>',
scope: { gridOptions: '=', rowClicked: "&", api: '=' },
controller: gridController,
controllerAs: 'vm',
bindToController: true
}
return directive;
}
angular.module("angularWithTS").directive("myDirective", MyDirective);
我的 Controller 类如下所示:
export class gridController {
public agGridOptions: any = {};
public api: any = {};
public gridOptions: any;
public rowClicked: any;
constructor() {
this.Process();
}
private Process() {
/*****Contoller Logic*****/
var columnDefs = commonFunctions.convertToAgColumns(this.gridOptions.columnDefinitions);
this.agGridOptions.enableSorting = true;
this.agGridOptions.editable = true;
this.agGridOptions.enableColResize = true;
this.agGridOptions.columnDefs = columnDefs;
/*****Contoller Logic*****/
/*****Exposed Events*****/
this.agGridOptions.onRowClicked = function (event) {
this.rowClicked({ index: event.rowIndex });
};
/*****Exposed Events*****/
/*****Public Api*****/
this.api = {
populateData: function (options) {
this.agGridOptions.api.setRowData(options.rowData);
}
}
}
/*****Public Api*****/
}
我在 html 中的指令标签如下所示
<my-directive grid-options="options" api="gridApi"></my-directive>
问题:当我尝试在 Controller 范围内调用 api 方法 populateData() 时,变量如 agGridOptions 未定义,然后 rest 不工作。 为什么当我调用公共(public) api 时变量 agGridOptions 不可用? 请帮助.. 当我编写普通的 js 函数方式 Controller 但不使用 typescript 类 Controller 时,它工作正常。任何帮助将不胜感激
我正在调用 Controller 方法,如下所示:
$scope.gridApi = {};
$scope.options = {};
$scope.options.columnDefinitions = $scope.columnDefinitions;
$http.get("monthlySales.json").then(function (response) {
$timeout(function () {
$scope.options.rowData = response.data;
$scope.gridApi.populateData($scope.options);
},2000);
});
当 Controller 第一次调用时, Controller 中的所有变量值(如 gridOptions、agGridOptions)都会正确获取。 但是当我调用 api populateData 来显示获取的数据时,agGridOptions 变得不确定。
最佳答案
您在函数中调用的“this”指的是函数本身,而不是您的 Controller -
this.api = {
populateData: function (options) {
this.agGridOptions.api.setRowData(options.rowData); //(this = populateData function)
}
}
语法应改为 () =>(这将使 typescript 编译器“传输”this,它将在 js 文件中变为 _this)
它应该是这样的:
this.api.populateData = (options)=> {
this.agGridOptions.api.setRowData(options.rowData);
}
关于javascript - 指令的angularjs typescript Controller 类中未定义的范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397234/