{{...">

AngularJS - change the value of a region when its key is true in another region

I have 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 checkthere is true, the symbol 🗸 is displayed, and when it is false, X

I have one more $scope.filter(which I use for other purposes, but for simplicity I’ll just write its contents)

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

What I would like, whenever I change the values $scope.filter, this change will be reflected in $scope.cars(therefore, in this example, if filter.producers.Ferrari:false, the corresponding element in $scope.carsalso automatically changes to'check':false

You can check jsfiddle here Thanks in advance!

: RipTheJacker, , , .

+4
3

. - filter :

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

jsFiddle.

​​ $scope.checkProducerTrue :

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

Using Angulars $ scope. $ watch you can "listen" to 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)
Run code

JSFiddle link here

+1
source

Source: https://habr.com/ru/post/1662421/


All Articles