关于如何在ngRepeat指令中实现项目删除,有许多问题。我发现,这可以通过使用ngClick并触发一些删除函数并传递它的索引$index来实现。
然而,我找不到任何一个同时包含多个ngRepeats的示例:
<div ng-controller="MyController">
<div ng-repeat="email in user.emails">
{{ email }} <a href>Remove</a>
</div>
<div ng-repeat="phone in user.phones">
{{ phone }} <a href>Remove</a>
</div>
</div>
为此,我需要创建 `$scope.removePhone` 和 `$scope.removeEmail`,并使用 `ngClick` 在“删除”链接上进行调用。但是,我正在寻找更通用的解决方案。特别是因为我有许多带有 `ngRepeats` 的页面。
我考虑编写一个指令,该指令将放置在“删除”链接上,并执行以下操作:
1. 在父元素中查找 `ngRepeat`。 2. 读取它正在迭代的内容(第一个示例中的“user.emails”,第二个示例中的“user.phones”)。 3. 从该模型中删除 `$index` 元素。
因此,标记看起来可能如下所示:
<div ng-controller="MyController">
<div ng-repeat="email in user.emails">
{{ email }} <a href remove-directive="$index">Remove</a>
</div>
<div ng-repeat="phone in user.phones">
{{ phone }} <a href remove-directive="$index">Remove</a>
</div>
</div>
我想知道我要实现的目标是否可能,并且应该采用哪种首选方法来实现?
当前的折中解决方案
这是我目前的做法。虽然不够优美但能完成任务,等我找到更好的方法再改进。
myAppModule.controller('MyController', function ($scope, $parse, $routeParams, User) {
$scope.user = User.get({id: $routeParams.id});
$scope.remove = function ($index, $event) {
// TODO: Find a way to make a directive that does this. This is ugly. And probably very wrong.
var repeatExpr = $($event.currentTarget).closest('[ng-repeat]').attr('ng-repeat');
var modelPath = $parse(repeatExpr.split('in')[1].replace(/^\s+|\s+$/g, ''));
$scope.$eval(modelPath).splice($index, 1);
};
});
在DOM中:
<div ng-repeat="email in user.email" class="control-group">
<label class="control-label">
{{ "Email Address"|_trans }}
</label>
<div class="controls">
<input type="text" ng-model="email.address">
<span class="help-inline"><a href ng-click="remove($index, $event)">{{ "Delete"|_trans }}</a></span>
</div>
</div>