gpt4 book ai didi

angularjs - ng-repeat 使用的 Angular 过滤器函数中未定义 `this`

转载 作者:行者123 更新时间:2023-12-01 04:52:11 25 4
gpt4 key购买 nike

我正在尝试过滤使用 ng-repeat 的 dom 中的数组。过滤器在我硬编码返回时起作用,但是当我尝试使用 this 时,它给了我错误

Cannot read property minHeight of undefined.



因此,由于某种原因,这是未定义的,但它适用于 Controller 中的其他功能。我不确定为什么它在过滤器中不起作用。

我确定我错过了一些非常简单的东西,但我找不到它

Controller
export class ItemComponent {

/*@ngInject*/
constructor($http) {
this.$http = $http;
this.minHeight = 0;
}

filter(row){
console.log(this.minHeight);
return row.minHeight > this.minHeight;
}

HTML
ng-repeat="item in itemCtrl.items | filter: itemCtrl.filter"

转译代码(来自浏览器中的 app.bundle.js)
var ItemsComponent = exports.ItemsComponent = function () {
/*@ngInject*/
ItemsComponent.$inject = ['$http'];
function ItemsComponent($http) {
_classCallCheck(this, ItemsComponent);

this.$http = $http;
this.minHeight = 0;
}

_createClass(ItemsComponent, [{
key: '$onInit',
value: function $onInit() {
this.loadItems();
}
}, {
key: 'loaditems',
value: function loadItems() {
var _this = this;

this.$http.get('/api/items').then(function (res) {
_this.items = res.data;
console.log(_this.items);
}).catch(function (err) {
console.log(err);
});
}
}, {
key: 'filter',
value: function filter(row) {
console.log(this.minHeight);

return row.minHeight > 3;
}
}]);

return ItemsComponent;
}();

最佳答案

我很确定这不是最好的方法,但是由于没有答案而且我可以通过这种方式解决我的问题,所以我将与您分享。

没有thisng-repeat 上调用时过滤器函数中的上下文(为什么?),所以我解决了它绑定(bind)上下文并从 this 获取 Controller 上下文语境。

HTML

ng-repeat="item in itemCtrl.items | filter: itemCtrl.filter.bind(this)"

Controller
filter(row) {
console.log(this.itemCtrl.minHeight);
}

关于angularjs - ng-repeat 使用的 Angular 过滤器函数中未定义 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40136241/

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