Angularjs 如何将值传递给Angular$interval函数 条件
我有一个使用ngRepeat构建的HTML元素数组Angularjs 如何将值传递给Angular$interval函数 条件,angularjs,Angularjs,我有一个使用ngRepeat构建的HTML元素数组 <li ng-repeat="person in persons">Name: {{ person.name }}. Age {{ person.age }}</li> 在我的控制器中,我尝试使用Angular$interval动态地更新随机人的年龄 $scope.persons = [ {name: "John Doe", age: 30}, {name: "Peter Parker", age: 21},
<li ng-repeat="person in persons">Name: {{ person.name }}. Age {{ person.age }}</li>
在我的控制器中,我尝试使用Angular$interval动态地更新随机人的年龄
$scope.persons = [
{name: "John Doe", age: 30},
{name: "Peter Parker", age: 21},
{name: "Clark Kent", age: 45},
{name: "John Wayne", age: 33}
];
var promiseOfYouth = [];
$scope.makeYoung = function() {
//since persons are store in array object.
//loop persons to update dynamically each person age
for(var x = 0; x < $scope.persons.length; x++) {
//check age randomizer already running
if ( angular.isDefined(promiseOfYouth[x]) ) return;
//make them young!
promiseOfYouth[x] = $interval(function() {
console.log('x value in $interval function: '+x);
try {
$scope.persons[x].age = Math.floor(Math.random() * (99 - 17 + 1)) + 17;
} catch(err) {
console.log('"$scope.persons['+x+'].age" is not valid. Error message:'+err.message);
}
}, 100, 50);
}
}
问题
在makeYoung函数中,x值始终返回4
问题
在这种情况下,如何将x的值传递到$interval函数中?
有关更多详细信息,请查看我的JSFIDLE示例您可以将其作为参数注入
promiseOfYouth[x] = $interval(function(x) {
console.log('x value in $interval function: '+x);
try {
$scope.persons[x].age = Math.floor(Math.random() * (99 - 17 + 1)) + 17;
} catch(err) {
console.log('"$scope.persons['+x+'].age" is not valid. Error message:'+err.message);
}
}, 100, 50);
这是一个经典的JavaScript。你需要在一个新的范围内有x才能使它工作。否则,所有闭包都使用相同x变量的值,即循环末尾的4 看 此解决方案的另一个优点是使代码更具可读性。这是javascript的一个优势。这篇博文提出了几种解决方案。将x变量复制为立即执行的函数:
(function(x2) {promiseOfYouth[x2] = $interval(function() {
console.log('x value in $interval function: '+x2);
try {
$scope.persons[x2].age = Math.floor(Math.random() * (99 - 17 + 1)) + 17;
} catch(err) {
console.log('"$scope.persons['+x2+'].age" is not valid. Error message:'+err.message);
}
}, 100, 50)}(x);
或者绑定函数
promiseOfYouth[x] = $interval(function(x2) {
console.log('x value in $interval function: '+x2);
try {
$scope.persons[x2].age = Math.floor(Math.random() * (99 - 17 + 1)) + 17;
} catch(err) {
console.log('"$scope.persons['+x2+'].age" is not valid. Error message:'+err.message);
}
}.bind(null, x), 100, 50);
感谢JSFIDLE示例和解释。JS闭包是一个我觉得很难理解的东西,但是这个问题确实帮助我从不同的角度来看待它。再次感谢。感谢您的博客链接:非常感谢您的分享!:
promiseOfYouth[x] = $interval(function(x2) {
console.log('x value in $interval function: '+x2);
try {
$scope.persons[x2].age = Math.floor(Math.random() * (99 - 17 + 1)) + 17;
} catch(err) {
console.log('"$scope.persons['+x2+'].age" is not valid. Error message:'+err.message);
}
}.bind(null, x), 100, 50);