如何根据angularjs中的其他属性将对象绑定到表达式?

时间:2013-06-02 16:37:20

标签: angularjs

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

$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

如何绑定这样的东西?

1 个答案:

答案 0 :(得分: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();
});