0

我有一个带有这个变量的角度项目:

$scope.kilometer = 20;
$scope.carType=1;

我想要那个

$scope.priceperkilometer

平等的

 10 if $scope.kilometer < 20 and $scope.carType=1
 20 if $scope.kilometer < 20 and $scope.carType=2
 30 if $scope.kilometer >= 20 and $scope.carType=1
 40 if $scope.kilometer >= 20 and $scope.carType=2

如何绑定这样的东西?

4

1 回答 1

1

具有该功能的变体确实有效。但是您也可以预先计算该值(如果您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();
});
于 2013-06-02T16:46:29.657 回答