在我的一个观点中,我使用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)]
真的有什么区别吗?我应该更喜欢一种方式而不是另一种方式吗?为什么?