`this` undefined in Angular filter function used by ng-repeat

I am trying to filter an array in dom that uses ng-repeat. The filter works when I hard code return, but when I try to use this, it gives me an error

Unable to read minHeight undefined property.

For some reason this is undefined, but works in other controller functions. I am not sure why it does not work in the filter.

I'm sure I miss something ridiculously simple, but I can't find it

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"

Transpiled Code (from app.bundle.js in the browser)

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;
}();
+4
source share
2 answers

, , , , .

this ng-repeat (?), this.

HTML

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

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

, , , , .

:

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

        // arrow function will bind the 'this' you need, or you could use '.bind' instead
        this.filter = (row) => {
            console.log(this.minHeight);
            return row.minHeight > this.minHeight;
       }
    }
0

Source: https://habr.com/ru/post/1658228/


All Articles