Joe82
Joe82

Reputation: 1251

AngularJS - change scope value when its key is true within another scope

I have a ng-repeat like this

<li ng-repeat="car in cars">
  <p>{{car.model}}</p>
  <span ng-show="car.check">🗸</span>
  <span ng-show="!car.check">X</span>
</li>

based on this $scope.cars

$scope.cars=[
    {'model':'Ford','check':true},
    {'model':'Honda','check':true},
    {'model':'Ferrari','check':true}
];

So when check is true, it is displayed a 🗸, and when it is false, a X

I have another $scope.filter (that I use for another purposes, but for the shake of simplicity I will just write its content)

$scope.filter = {
  "producers": {
    "Ford": true,
    "Honda": true,
    "Ferrari": false
    }
}

What I would like is whenever I change the $scope.filter values, that change would be reflected in the $scope.cars (so in this example, if filter.producers.Ferrari:false, the corresponding element in $scope.carswould automatically change as well to 'check':false

You can check the jsfiddle here Thanks in advance!

Edit: as RipTheJacker says, the question is about how to make a function that updates the cars checked value based on the filter values.

Upvotes: 4

Views: 79

Answers (3)

probablykabari
probablykabari

Reputation: 1389

Update

I missed the original requirement to update the value. The easiest way is to watch the filter model from your scope:

$scope.$watch("filter", function(nv,ov){
  angular.forEach($scope.cars, function(car){
    car.check = nv.producers[car.model]
  })
}, true)

Upvotes: 1

TRDrake
TRDrake

Reputation: 212

With Angulars' $scope.$watch you can "listen" changes in variables. I leave you a very simple example based on your JSFiddle... you should optimize the function but i think the idea is clear.

  $scope.$watch('filter.producers',function(s){
	$scope.cars[0].check = $scope.filter.producers.Ford;
  $scope.cars[1].check = $scope.filter.producers.Honda;
  $scope.cars[2].check = $scope.filter.producers.Ferrari;
},true)

Link to JSFiddle here

Upvotes: 1

taguenizy
taguenizy

Reputation: 2265

I've updated your jsFiddle.

Basically just updated your $scope.checkProducerTrue function to:

$scope.checkProducerTrue = function(c) {
   angular.forEach($scope.filter.producers, function(value, key) {
       if (key == c.model) c.check = value;
   });
};

Upvotes: 1

Related Questions