gpt4 book ai didi

javascript - 当一个值改变时如何改变另一个值

转载 作者:行者123 更新时间:2023-11-27 23:57:18 25 4
gpt4 key购买 nike

我有例如这样的代码:

scope.people;
scope.agedPeople;

如果人们重视改变,我需要这样做:

scope.agedPeople = scope.people * 0.3;

如果gedPeople 值发生变化,我需要这样做:

scope.people = scope.agedPeople / 0.3;

我想使用 $watch,但正如你所看到的,我有循环引用......我这样解决了它:

    scope.checkIsPeopleCounted = function() {
var countedPeople;

countedPeople = scope.agedPeople * 0.3;

return countedPeople === scope.people;
};


scope.checkIsAgedPeopleCounted = function() {
var countedAgedPeople;

countedAgedPeople = scope.people / 0.3;

return countedAgedPeople === scope.agedPeople;
};

scope.$watch('people', function() {
!scope.checkIsAgedPeopleCounted() && (scope.agedPeople = scope.people / 0.3);
});

scope.$watch('agedPeople', function() {
!scope.checkIsPeopleCounted() && (scope.people = scope.agedPeople * 0.3);
});

不过看起来不太好。也许还有另一种解决方案?

如何将其做成 Angular ?

最佳答案

如果没有更多信息,这有点困难。但理论上你可以像这样观察范围内的值:

$scope.$watch('agedPeople', function(newValue, oldValue){});

请参阅 Scope 文档。$watch: Angular Scope.$watch documentation .

但在你的情况下,你有一个循环引用。您可以通过向返回结果的范围添加方法来解决此问题。

var MULTIPLIER = .3;
$scope.agedPeople = 1;
$scope.people = 1;

$scope.getAgedPeople = function () {
return $scope.people * MULTIPLIER;
};

$scope.getPeople = function () {
return $scope.agedPeople * MULTIPLIER;
};

希望对您有所帮助!

关于javascript - 当一个值改变时如何改变另一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32154754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com