0

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?

2
  • what about using a function $scope.priceperkilometer=function(){} since that variable depends on other variables it makes more sence to do that. Commented Jun 2, 2013 at 16:40
  • yes. That what i'm start to think about. Do you thinks it will refresh the display ? Commented Jun 2, 2013 at 16:41

1 Answer 1

1

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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.