Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用angular2中的局部变量值?_Javascript_Angular - Fatal编程技术网

Javascript 如何使用angular2中的局部变量值?

Javascript 如何使用angular2中的局部变量值?,javascript,angular,Javascript,Angular,我有一个简单的函数,它将值作为数字返回给我。该值基本上表示todolist中有多少项不完整 testFunction() { var a = 0; this.todos.forEach(function(elem, i) { if(elem.status === true) { a += 1; } })

我有一个简单的函数,它将值作为数字返回给我。该值基本上表示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}}//这里什么都没有?

如何在模板中记录
a
的值Angular只能使用组件自己的数据字段将数据绑定到模板。因此,您的代码需要如下所示

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语法,您甚至不需要绑定
this
您可以使用一个箭头函数,从父范围传递
this

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

将其作为组件的属性您需要将变量定义为函数外部的private/public,作为您的类成员。简单地说,将
a
定义为
this,而不是
var
,a=0我已经这样做了@FrankModica导出类SomeComponent实现了OnInit{todos:Todo[];a:any;以及a:numbers这样你就不需要在方法内部定义你的
a
。删除
var a=0;
put而不是
this.a=0
和循环内部使用
this.a+=1
为什么绑定,先生?我想我错过了那部分。看看这个链接@Mike绑定是用来保存f内部的值的如果不是,那么使用arraow函数如果您想使用ES6语法,您只需要为(this.todos的常量){…}