2

I have a simple function that returns me the value as number. This value basically how many items in a todolist is incomplete.

testFunction() {
    var a = 0;
    this.todos.forEach(function(elem, i) {
                    if(elem.status === true) {
                        a += 1;
                    }
                })
                console.log(a); // gives correct length
    }

Now in view I have

Total todo Items  Left <span>{{a}}</span> //Nothing coming here?

How do I log the value of a in template

Mike
  • 3,348
  • 11
  • 45
  • 80

1 Answers1

1

Angular can bind data to template only using own data fields of the component. So your code need to be as follows

testFunction() {
    this.a = 0;
    this.todos.forEach(function(elem, i) {
        if(elem.status === true) {
            this.a += 1;
        }
    }.bind(this))
    console.log(a); // gives correct length
}

UPD If you want to use ES6 syntax, you even do not need to bind this you can just use an arrow function which passes this from parent scope:

testFunction() {
    this.a = 0;
    this.todos.forEach((elem, i) => {
        if(elem.status === true) {
            this.a += 1;
        }
    })
    console.log(a); // gives correct length
}
MysterX
  • 2,318
  • 1
  • 12
  • 11
  • Why that bind sir? I missed that part I think. – Mike Jul 31 '17 at 13:10
  • 1
    Look at this link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – MysterX Jul 31 '17 at 13:11
  • 1
    @Mike the bind is used to preserve the value of this inside of a function if not then use arraow functions [link](https://stackoverflow.com/questions/45295467/how-to-access-this-variable-inside-this-function/45295586#45295586) – Rahul Singh Jul 31 '17 at 13:16
  • If you wanted to use ES6 syntax, you would just have written `for (const elem of this.todos) { … }` – Bergi Jul 31 '17 at 13:25