[英]What's the best way to keep an object property linked to a value?
My question is related to a directive that I have refactored: 我的问题与我重构的指令有关:
HTML HTML
<!-- Before -->
<slider value="sliderValue" floor="0" ceil="maxPrice"></slider>
<!-- New version -->
<slider value="sliderValue" options="sliderOptions"></slider>
<!-- Both directives use '=' bindings... -->
JS 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 ceil
in the directive. 使用旧版本,我可以更新
$scope.maxPrice
,它将自动更新指令中ceil
的作用域值。 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. 我想到的第一个主意是在
$scope.maxPrice
上使用$watch
,但是我读过很多人解释说,使用$watch
是不好的做法。
Then, I could update $scope.sliderOptions.ceil
manually every time I update $scope.maxPrice
but this is quite annoying. 然后,我可以在每次更新
$scope.sliderOptions.ceil
手动更新$scope.maxPrice
但这很烦人。
NB $scope.maxPrice
is a business-logic value used in several places of the application while $scope.sliderOptions
is only used for the slider directive. 注意:
$scope.maxPrice
是在应用程序的多个位置中使用的业务逻辑值,而$scope.sliderOptions
仅用于滑块指令。
After giving it some thought and discussion I guess you're limited to wrapping maxprice
in an simple object. 经过思考和讨论,我想您仅限于将
maxprice
在一个简单的对象中。 The reason to do so would be because JavaScript can't pass numbers by reference. 这样做的原因是因为JavaScript无法通过引用传递数字。 More information on the topic: Is there thing like pass by value pass by reference in JavaScript?
有关主题的更多信息: 是否有类似JavaScript中按值传递和引用传递的东西?
Proposed solution 拟议的解决方案
$scope.sliderValue=0;
$scope.maxPrice = {value: 1000};
$scope.sliderOptions = {
floor: 0,
ceil: $scope.maxPrice
};
//later
$scope.maxPrice.value = 2000;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.