gpt4 book ai didi

javascript - AngularJS 从数组中计算两个动态值

转载 作者:行者123 更新时间:2023-11-28 05:42:18 25 4
gpt4 key购买 nike

我是 Web 开发新手,在 AngularJS 中遇到了数组问题。

我有一个 ng-repeat 序列。此序列中有两个 slider ,由于 ng-repeat 的作用而一遍又一遍地重复。

相应的 HTML 代码片段如下所示:

<h1>INDEX = {{index}}</h1>
<div ng-repeat="alert in alerts">
<rzslider rz-slider-model="alert.value"
rz-slider-options="alert.options"></rzslider>
<br>
<br>
<div>
<h4>{{alert.weighttitle}}</h4>
<div>
<md-slider flex md-discrete ng-model="alert.weight" step="1" min="1" max="100" aria-label="rating"></md-slider>
</div>
</div>
</div>

考虑到所有链接和脚本都已包含并且 Controller 已正确设置。

上面的代码执行以下操作:

  • 它显示来自 angularJS Controller 的 $scope.index。
  • 出现两个不同的 slider ,循环访问称为警报的数组。从那里它需要一些值。

Controller 的有趣片段如下所示:

$scope.alerts = [
{ id: 1,
title: 'title1',
weighttitle: 'weighttitle1',
value: 1,
weight: 10,
options: {
showTicks: true,
hidePointerLabels: true,
hideLimitLabels: true,
stepsArray: [
{ value: 1, legend: '<10' },
{ value: 2, legend: '<50' },
{ value: 3, legend: '<250' },
{ value: 4, legend: '<500' },
{ value: 5, legend: '>500' }

]
}
},
{ id: 2,
title: 'title2',
weighttitle: 'weighttitle2',
value: 5,
weight: 1,
options: {
showTicks: true,
hidePointerLabels: true,
hideLimitLabels: true,
stepsArray: [
{ value: 1, legend: '<2Mio' },
{ value: 2, legend: '<10Mio' },
{ value: 3, legend: '<50Mio' },
{ value: 4, legend: '<100Mio' },
{ value: 5, legend: '>100Mio' }

]
}
},
{ id: 3,
title: 'title3',
weighttitle: 'weighttitle3',
value: 1,
weight: 1,
options: {
showTicks: true,
hidePointerLabels: true,
hideLimitLabels: true,
stepsArray: [
{ value: 1, legend: '<5%' },
{ value: 2, legend: '<10%' },
{ value: 3, legend: '<15%' },
{ value: 4, legend: '<20%' },
{ value: 5, legend: '>20%' }

]
}
},
{ id: 4,
title: 'title4',
weighttitle: 'weighttitle4',
value: 3,
weight: 69,
options: {
showTicks: true,
hidePointerLabels: true,
hideLimitLabels: true,
stepsArray: [
{ value: 1, legend: '<5' },
{ value: 2, legend: '<10' },
{ value: 3, legend: '<15' },
{ value: 4, legend: '<20' },
{ value: 5, legend: '>20' }

]
}
},
];

上面的代码片段是 Controller 的一部分,它正确地包含在 HTML 中,因此可以正常工作。

我现在的问题是如何设置 $scope.index 以便它从数组并相应地乘以值,例如 value * Weight必须注意的是,用户可以通过更改操纵 slider 来更改此值,该 slider 对应于数组中的特定变量

我尝试了这样的 $watch 命令:

$scope.$watch('alerts', function(newValue, oldValue){
$scope.index = oldValue + (newValue.weight * newValue.value);
}, true);

但是它不起作用。

最佳答案

您可以使用$scope.$watch并监听更改,当发生更改时您可以更新 View 。您还可以尝试使用 ng-change="update(alert)" 函数并将值传递给函数。

关于javascript - AngularJS 从数组中计算两个动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38826120/

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