Angular replace data from ng-repeat element

Consider this code:

<div ng-repeat="car in cars() | filter: car.owned == true">
    <a href="" ng-click="selectCar(car)">{{ car.name }}</a>
    ...
</div>

In the directive, ng-clickI call a function selectCar(), passing data caras a parameter. Is it possible to replace the data carafter ng-repeat? So, when I click on the binding element, will the new data be passed as a parameter?

How can i do this?

0
source share
1 answer

The problem is that it ng-repeatcreates a new scope for each list item. Thus, in all these areas there is another property car. Your method is selectCar()defined in the parent scope, though if you would do something like:

$scope.selectCar = function(car) {
  $scope.car = newCar;
}

, car . - , selectCar(). - :

$scope.selectCar = function(car) {
  var newCar = ...;
  for (var key in newCar) {
    car[key] = newCar[key];
  }
}

. - , ng-repeat . - :

myModule.directive('repeatClick', ['$parse', function($parse) {
  return {
    restrict: 'A',
    compile: function($element, attr) {
      var fn = $parse(attr['repeatClick']);
      return function(scope, element, attr) {
        element.on('click', function(event) {
          scope.$apply(function() {
            fn(scope, {$event: event, $scope: scope});
          });
        });
      };
    }
  };
}]);

HTML- :

<a href="" repeat-click="selectCar(car, $scope)">{{ car.name }}</a>

:

$scope.selectCar = function(car, $repeatScope) {
  var newCar = ...;
  $repeatScope.car = newCar;
}

: http://jsbin.com/dupiraju/2/edit

, . selectCar() ng-repeat, this . repeat-click selectCar() :

$scope.selectCar = function(car) {
  var newCar = ...;
  this.car = newCar;
}
+1

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


All Articles