gpt4 book ai didi

javascript - 使用 typescript 从回调中获取 Controller 引用

转载 作者:行者123 更新时间:2023-12-02 15:00:09 28 4
gpt4 key购买 nike

我有以下简单的 Controller ,它使用指令/组件并传递函数作为绑定(bind)。

当函数被调用时,我没有引用使用任何 Controller 类服务。

在这种情况下,在我的 Controller public onTileClicked函数中,我无权访问tileService

Controller js:

namespace app.dashboard {
'use strict';

export class DashboardController {
static $inject:Array<string> = ['$q', 'logger', 'tileService'];

constructor(private $q:ng.IQService,
private tileService:TileService) {
}

public tiles:Array<ITile> = [];

public onTileClicked(tile:ITile) {
this.tileService.getTiles(tile.ID) // No access to tileService
.then((data)=> {
this.tiles = data; // Won't have access to this.tiles
})
}
}

angular
.module('app.dashboard')
.controller('DashboardController', DashboardController);
}

Controller html:

<div class="tiles-container">
<tile-component ng-repeat="tile in DashboardCtrl.tiles" tile="tile"
on-tile-clicked="DashboardCtrl.onTileClicked">
</tile-component>
</div>

指令js:

class TileComponent {
tile:ITile;
onTileClicked:Function;

/* @ngInject */
constructor() {
}

tileClicked() {
this.onTileClicked()(this.tile);
}
}

angular.module('app.dashboard')
.component('tileComponent', {
templateUrl: 'app/dashboard/directives/tile.html',
controller: TileComponent,
controllerAs: 'tileCtrl',
bindings: {
tile: '<',
onTileClicked: "&"
}
});

onTileClicked js:

DashboardController.prototype.onTileClicked = function (tile) {
var _this = this;
this.tileService.getTiles(tile.ID)
.then(function (tiles) {
_this.tiles = tiles;
});
};

最佳答案

您对函数的绑定(bind)(在 html 中)是错误的。您错过了括号:

<tile-component ng-repeat="tile in DashboardCtrl.tiles" tile="tile"
on-tile-clicked="DashboardCtrl.onTileClicked()"> <!-- HERE -->
</tile-component>

关于javascript - 使用 typescript 从回调中获取 Controller 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35484885/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com