具有该功能的变体确实有效。但是您也可以预先计算该值(如果您priceperkilometer
经常使用,这可能会更快):
$scope.kilometer = 20;
$scope.carType = 1;
calculatePrice = function() {
if ($scope.kilometer < 20 and $scope.carType=1)
return 10;
else if ($scope.kilometer < 20 and $scope.carType=2)
return 20;
else if ($scope.kilometer >= 20 and $scope.carType=1)
return 30;
else if ($scope.kilometer >= 20 and $scope.carType=2)
return 40;
};
$scope.priceperkilometer = calculatePrice();
$scope.$watch('kilometer', function(newValue, oldValue) {
if (newValue != oldValue)
$scope.priceperkilometer = calculatePrice();
});
$scope.$watch('carType', function(newValue, oldValue) {
if (newValue != oldValue)
$scope.priceperkilometer = calculatePrice();
});