我需要实时计算并显示一些依赖于其他 2 个变量的值。
我成功观看了其中一部,但没能同时观看两部。
$scope.color_slider_bar = {
value:0,
minValue: 0,
maxValue: 100,
options: {
ceil: 100,
floor: 0,
translate: function (value) {
return value + ' CHF';
},
showSelectionBar: true,
getSelectionBarColor: function(value) {
if (value >= 0)
return '#00E3C6';
},
onEnd: function () {
$scope.priceselected = $scope.color_slider_bar.value;
console.log($scope.priceselected);
}
}
};
$scope.selectOffer = function(offer){
$scope.companydata.selectedoffer.push(offer)
$scope.$watch(['$scope.companydata.selectedoffer', '$scope.priceselected'], function() {
if ($scope.companydata.selectedoffer.length == 1){
$scope.finalprice = $scope.priceselected;
console.log($scope.finalprice);
}
else if ($scope.companydata.selectedoffer.length == 2){
$scope.finalprice = $scope.priceselected / 2;
console.log($scope.finalprice);
}
else if ($scope.companydata.selectedoffer.length == 3){
$scope.finalprice = $scope.priceselected / 3;
console.log($scope.finalprice);
}
});
}
在第一个函数( slider )上,我定义了 $scope.priceselected。 第二个会将元素推送到 $scope.companydata.selectedoffer 中。
这里是 HTML:
<div class="col-xs-12" ng-repeat="offer in offers" ng-class="{'selected': offer.chosen}">
<div class="worditem" ng-show="!offer.chosen" ng-click="selectOffer(offer)">
<div class="table">
<div class="table-cell numbers">
<div class="title">{{offer.name}}</div>
<div class="info">{{offer.info}} / {{offer.views}}</div>
<a data-toggle="modal" data-target="#{{offer.price}}">+ INFO</a>
</div>
</div>
</div>
<div class="worditem" ng-show="offer.chosen" ng-click="unselectOffer(offer)">
<div class="overlay-price">{{finalprice | number : 0}}<br>CHF</div>
<div class="table">
<div class="table-cell numbers">
<div class="title">{{offer.name}}</div>
<div class="info">{{offer.info}} / {{offer.views}}</div>
<a data-toggle="modal" data-target="#{{offer.price}}">+ INFO</a>
</div>
<div class="overlay" ng-show="offer.chosen">
</div>
</div>
</div>
</div>
现在,当我将元素推送到 $scope.companydata.selectedoffer 或从 $scope.companydata.selectedoffer 中取消推送时,会重新计算 $scope.finalprice 的值,但在移动 slider 时不会重新计算(因此会更改 $scope.priceselected 的值
我错过了什么?
请您参考如下方法:
您不需要watch
来分配新值。请改用 Angular 双向绑定(bind)。
现在,如果您的 color_slider_bar.onEnd()
工作正常,那么只需删除 watch
函数,因为新值会自动绑定(bind),并且您的代码将正常工作。
$scope.selectOffer = function(offer){
$scope.companydata.selectedoffer.push(offer)
//$scope.$watch(['$scope.companydata.selectedoffer', '$scope.priceselected'], function() {
if ($scope.companydata.selectedoffer.length == 1){
$scope.finalprice = $scope.priceselected;
console.log($scope.finalprice);
}
else if ($scope.companydata.selectedoffer.length == 2){
$scope.finalprice = $scope.priceselected / 2;
console.log($scope.finalprice);
}
else if ($scope.companydata.selectedoffer.length == 3){
$scope.finalprice = $scope.priceselected / 3;
console.log($scope.finalprice);
}
//});
}
希望有帮助。