gpt4 book ai didi

javascript - 如何在 angular2 中使用局部变量值?

转载 作者:行者123 更新时间:2023-11-30 21:18:37 25 4
gpt4 key购买 nike

我有一个简单的函数,它以数字形式返回值。这个值基本上是一个 todolist 中有多少项目是不完整的。

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

现在我看到了

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

如何在模板中记录a的值

最佳答案

Angular 只能使用组件自己的数据字段将数据绑定(bind)到模板。所以你的代码需要如下所示

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 如果你想使用 ES6 语法,你甚至不需要绑定(bind) this 你可以只使用一个传递 this 的箭头函数> 来自父范围:

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

关于javascript - 如何在 angular2 中使用局部变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45416568/

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