0

Consider this code:

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

On the ng-click directive, I'm invoking a function selectCar(), passing the car data as a parameter. Will it be possible to replace the car data after the ng-repeat? So that when I click the anchor element, the new data will be passed as parameter?

How can I do this?

1
  • I've updated my answer with a simpler way to solve this. Commented Mar 21, 2014 at 12:43

1 Answer 1

1

The problem here is that ng-repeat creates a new scope for every list item. So there's a different car property in all those scopes. Your selectCar() method is defined on the parent scope though, so if you'd do something like:

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

It wouldn't have any effect since you're setting the car property on the parent scope. One option is to modify the object that you send to selectCar(). Something like:

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

But that's not a very nice way to solve it. Another option is to create a new directive that passes the ng-repeat scope into the event handler. Something like this:

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

That allows you to write your HTML like this:

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

And your click handler:

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

Here's an example: http://jsbin.com/dupiraju/2/edit

EDIT

My mistake, there's a much simpler way to do this. Your selectCar() method is going to be invoked on the ng-repeat scope, and you have access to it with this inside the function. So you can remove the repeat-click directive, and just change your selectCar() method to this:

$scope.selectCar = function(car) {
  var newCar = ...;
  this.car = newCar;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.