我有这样的代码:
scope.people;
scope.agedPeople;
如果人们重视变化,我需要这样做:
scope.agedPeople = scope.people * 0.3;
如果老年人重视变化,我需要这样做:
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);
});
但看起来不是很好。也许有另一种解决方案?
如何以角度制作?
答案 0 :(得分:1)
没有更多信息,它有点难。但从理论上讲,你可以像这样观察范围内的值:
$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;
};
我希望有所帮助!
答案 1 :(得分:0)
scope.$watch("people",function(){
scope.agedPeople = scoped.people * 0.3;
});
对老年人来说同样的事情