mcbjam
mcbjam

Reputation: 7454

How to bind an object to an expression depending on other attribut in angularjs?

I have an angular project with this variable :

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

I would like that

$scope.priceperkilometer

equal

 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

How to bind something like this?

Upvotes: 0

Views: 32

Answers (1)

TheHippo
TheHippo

Reputation: 63139

The variant with the function does work. But you also could pre-calculate the value (this might be faster if you use priceperkilometer often):

$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();
});

Upvotes: 1

Related Questions