angularjs – `this`在ng-repeat使用的角度滤波函数中未定义

前端之家收集整理的这篇文章主要介绍了angularjs – `this`在ng-repeat使用的角度滤波函数中未定义前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试过滤使用ng-repeat的dom中的数组.当我对返回进行硬编码时,过滤器有效,但是当我尝试使用它时,它会给我错误

Cannot read property minHeight of undefined.

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

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

调节器

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;
}();

解决方法

我很确定这不是最好的方法,但由于没有答案,我可以用这种方式解决我的问题,我会与你分享.

当在ng-repeat上调用时,过滤器函数中没有这个上下文(为什么?),所以我解决了绑定上下文并从此上下文获取控制器上下文的问题.

HTML

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

调节器

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

猜你在找的Angularjs相关文章