从NG-重复项角替换数据 [英] Angular replace data from ng-repeat item

查看:111
本文介绍了从NG-重复项角替换数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个code:

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

NG-点击指令,我调用一个函数 selectCar(),通过了数据作为参数。这将有可能取代数据 NG重复后?所以,当我点击了锚元素,新的数据将作为参数传递?

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?

推荐答案

这里的问题是, NG-重复创建每个列表项目的新范围。所以这是一个不同的属性在所有这些领域。你的 selectCar()方法虽然对父范围定义的,所以如果你愿意做这样的事情:

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

这不会有任何影响,因为你设置属性父范围。一种选择是修改您发送给 selectCar对象()。是这样的:

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

但是,这不是解决它一个非常好的方式。另一种选择是创建一个通过 NG-重复范围到事件处理程序的新指令。事情是这样的:

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

这允许你写你的HTML是这样的:

That allows you to write your HTML like this:

<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-重复范围被调用,你必须将其与访问这个里面的功能。所以,你可以删除重复点击指令,只是改变你的 selectCar()方法如下:

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

这篇关于从NG-重复项角替换数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆