【发布时间】:2013-07-26 11:37:50
【问题描述】:
在我的一个观点中,我使用 ng-repeat 指令来列出我的产品(属性无关):
<div ng-controller="MainCtrl>
<table>
<tr ng-repeat="product in products">
<td>{{product.name}}</td>
<td><input type="button" ng-click="removeProduct(product)"/></td>
</tr>
</table>
</div>
MainCtrl如下:
myApp.controller('MainCtrl', function($scope){
$scope.products = [...];
$scope.removeProduct = function(product){
}
});
我的问题与 removeProduct() 函数和实现它的最佳方式有关。
据我了解:
ng-repeat 在每次重复中创建一个新范围(我们称之为 $local)
$local 继承自 $scope,而 $scope 又继承自根范围
在 removeProduct() 函数内部 $scope 指的是 $scope 而 this 指的是 $local
$scope 和 $local 都可以访问 removeProduct() 中的产品。 $local 具有访问权限,原因是从 $scope 继承产品
在 removeProduct() 中,我需要一种方法来找到传递的产品的索引并从数组中拼接它。
我可以通过 3 种方式实现这一点:
使用 $scope.products
使用 this.products
不使用上述任何方法,并将产品作为第二个参数传递给视图中的函数 [removeProduct(product, products)]
真的有区别吗?我应该更喜欢一种方式而不是另一种方式吗?为什么?
【问题讨论】: