pavel06081991
pavel06081991

Reputation: 627

when one value changes how to change another value

I have for example such code:

scope.people;
scope.agedPeople;

If people value changes I need to do this:

scope.agedPeople = scope.people * 0.3;

And if agedPeople value changes I need to do this:

scope.people = scope.agedPeople / 0.3;

I wanted to use $watch, but as you can see I have the circular references... I solved it like this:

    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);
});

but it looks not very good. maybe there is another solution?

How to make it in angular?

Upvotes: 1

Views: 176

Answers (2)

Martin at Mavrix
Martin at Mavrix

Reputation: 244

Its a bit hard without more info. But in theory you can watch values on the scope like so:

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

See documentation for Scope.$watch: Angular Scope.$watch documentation.

But in your case you have a circular references. You can solve this by adding methods to the scope that returns the result instead.

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

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

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

I hope that helps!

Upvotes: 1

Ced
Ced

Reputation: 1301

scope.$watch("people",function(){
    scope.agedPeople = scoped.people * 0.3;
});

And the same thing for agedPeople

Upvotes: 0

Related Questions