2

My question is related to a directive that I have refactored:

HTML

<!-- Before -->
<slider value="sliderValue" floor="0" ceil="maxPrice"></slider>

<!-- New version -->
<slider value="sliderValue" options="sliderOptions"></slider>

<!-- Both directives use '=' bindings... -->

JS

$scope.sliderValue=0;
$scope.maxPrice = 1000;

$scope.sliderOptions = {
    floor: 0,
    ceil: $scope.maxPrice
};

//later
$scope.maxPrice = 2000;

With the old version, I could update $scope.maxPrice, and it would automatically update the scope value of ceilin the directive. I would like to achieve the same with the new version.

The first idea to come to my mind is using a $watch on $scope.maxPrice, but I have read many people explaining that using $watch is a bad practice.

Then, I could update $scope.sliderOptions.ceil manually every time I update $scope.maxPrice but this is quite annoying.

N.B. $scope.maxPrice is a business-logic value used in several places of the application while $scope.sliderOptions is only used for the slider directive.

ValentinH
  • 928
  • 1
  • 11
  • 31
  • Ah, I see! I can post you an answer using a service. It might require reworking some of your code but I'm quite confident it would be best for the structure of your application. Interested? – Maarten Bicknese Nov 24 '15 at 08:08
  • I'm not sure of what you want to do but the directive can't access a service since it can be reused in any application. – ValentinH Nov 24 '15 at 08:25

1 Answers1

0

After giving it some thought and discussion I guess you're limited to wrapping maxprice in an simple object. The reason to do so would be because JavaScript can't pass numbers by reference. More information on the topic: Is there thing like pass by value pass by reference in JavaScript?

Proposed solution

$scope.sliderValue=0;
$scope.maxPrice = {value: 1000};

$scope.sliderOptions = {
    floor: 0,
    ceil: $scope.maxPrice
};

//later
$scope.maxPrice.value = 2000;
Community
  • 1
  • 1
Maarten Bicknese
  • 1,498
  • 1
  • 14
  • 27
  • I understand that numbers can't be passed by reference. However, I don't like this solution because I have dozens of options that can be passed to the slider and I don't want to force the user to do `{floor: {value:0}, ceil: {value: $scope.maxPrice}, etc...}`. Also, since `$scope.maxPrice` belongs to business logic, I don't like the idea of modifying it because the slider needs it to have a mandatory structure. – ValentinH Nov 24 '15 at 09:12