gpt4 book ai didi

javascript - TypeScript angularjs 事件绑定(bind)

转载 作者:行者123 更新时间:2023-11-27 22:46:58 25 4
gpt4 key购买 nike

我最近开始使用 AngularJS + TypeScript 进行开发,并且对此还很陌生。

目前,我在通过滚动事件访问 Controller 属性时遇到问题。

类型文件如下所示:

module controller {

'use strict';

export class MyController {
public static $inject = ['$location', '$route', '$q', '$document'];
public listModel: object[];
public filterModel: model.FilterModel;
public pageLoading: boolean = false;
public pageIndex: number = 0;

constructor(
private $location: ng.ILocationService,
private $route,
private $q: ng.IQService,
private api: services.contentApi,
private $document
) {
$document.scroll(this.lazyScrollHandler);
}

init() {

var vm = this;
vm.api.filterContentItems(null, 0).then(l => {
vm.listModel = l;
});
}

private lazyScrollHandler() {
var vm = this;
if (vm.pageLoading == true)
return false;

var wintop = window.pageYOffset;
var scrollHeight = window.document.body.scrollHeight;
var offsetHeight = window.document.body.offsetHeight;
var triggered = (wintop / (scrollHeight - offsetHeight)) * 100;

if (triggered >= 80) {
vm.api.filterContentItems(vm.filterMode, 0).then(l => {
l.forEach((i, idx) => {
vm.listModel.push(i);
});
vm.pageLoading = false;
});
}
}
filter() {
var vm = this;
vm.api.filterContentItems(vm.filterMode, 0).then(l => {
vm.listModel = l;
});
}
}
var controllerId = 'contentItems';
(<any>angular.module('app')).lazy.controller(controllerId, MyController);
}

HTML 部分如下所示:

<div class="panel" data-ng-controller="contentItems as vm" ng-init="vm.init()" ><div class="articles-list">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-3">
<label>Culture Info:</label>
<input ng-model="vm.filterModel.cultureInfo"></input>
</div>
</div>
</div>
</div>
</div>
<div>
<div class="row">
<button ng-click="vm.filter()">Filter</button>
</div>
</div>
<table class="table table-articles" id="grid" >
<thead>
<tr>
<th>Title</th>
<th>Culture Info</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ct in vm.listModel">
<td>{{ct.title}}</td>
<td>{{ct.cultureInfo}}</td>
</tr>
</tbody>
</table>
</div>

init()filter()调用“this”时的方法是当前 Controller /作用域。当lazyScrollHandler()被称为“this”的不是当前 Controller /作用域,而是 HTMLDocument,这使得“vm”变量中的所有属性都未定义。

我错过了什么?我做错了什么?

最佳答案

尝试将方法 lazyScrollHandler() 更改为属性定义:

//private lazyScrollHandler() {
private lazyScrollHandler = () => {
...
}

关于javascript - TypeScript angularjs 事件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38355386/

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