angularjs $watch函数如何与滑块一起工作
How does angulars $watch function work with slider
各位。我是 Web 开发的新手,遇到了一个问题。我终于设法为我的问题创建了一个 fiddle 以变得更具体。
我的问题是我有 2 个滑块。一个 Slider 负责值,另一个负责权重。这些滑块使用 ng-repeat 函数重复 n 次。在fiddle中只出现了两次,仅供演示。
我想计算一个由以下公式组成的指数:
Value1*Weight1+Value2*Weight2
索引是用reduce函数计算的。 问题是:当值因滑块变化而变化时,索引值未更新
我很确定它应该与 $watch 函数一起使用,但不幸的是我不知道如何管理它。
如果有人能这么好心帮帮我。
js fiddle 链接如下。
如果您想根据对警报的更改更新作用域上的索引 属性,您应该对警报进行深入观察:
$scope.$watch('alerts', function() {
var index = $scope.alerts.reduce(function(prev, next) {
return prev + (next.value*next.weight);
}, 0);
$scope.index = index;
console.log(index);
}, true);
你可以用这样的方式重构你的代码:
$scope.index = 0;
$scope.calcIndex = function(){
return $scope.alerts.reduce(function(prev, next) {
return prev + (next.value*next.weight);
}, 0);
};
$scope.$watch(function(){
return $scope.calcIndex();
}, function(newValue){
$scope.index = newValue;
});
各位。我是 Web 开发的新手,遇到了一个问题。我终于设法为我的问题创建了一个 fiddle 以变得更具体。
我的问题是我有 2 个滑块。一个 Slider 负责值,另一个负责权重。这些滑块使用 ng-repeat 函数重复 n 次。在fiddle中只出现了两次,仅供演示。
我想计算一个由以下公式组成的指数:
Value1*Weight1+Value2*Weight2
索引是用reduce函数计算的。 问题是:当值因滑块变化而变化时,索引值未更新 我很确定它应该与 $watch 函数一起使用,但不幸的是我不知道如何管理它。
如果有人能这么好心帮帮我。
js fiddle 链接如下。
如果您想根据对警报的更改更新作用域上的索引 属性,您应该对警报进行深入观察:
$scope.$watch('alerts', function() {
var index = $scope.alerts.reduce(function(prev, next) {
return prev + (next.value*next.weight);
}, 0);
$scope.index = index;
console.log(index);
}, true);
你可以用这样的方式重构你的代码:
$scope.index = 0;
$scope.calcIndex = function(){
return $scope.alerts.reduce(function(prev, next) {
return prev + (next.value*next.weight);
}, 0);
};
$scope.$watch(function(){
return $scope.calcIndex();
}, function(newValue){
$scope.index = newValue;
});