删除元素会留下ng-repeat注释

Removing elements leaves behind ng-repeat comments

本文关键字:ng-repeat 注释 元素 删除      更新时间:2023-09-26

我做了一个清单,列出了一些项目,有些项目允许你点击它们来查看类似的项目。当我在用户关闭列表后删除类似的item元素时,它留下了…

<!-- ngRepeat: item in category.items(3606) | orderBy:'sort_order' -->
<!-- end ngRepeat: item in category.items(3606) | orderBy:'sort_order' -->

会导致问题,因为每当这些项在作用域中被更新时,angular就会重新创建ng-repeat并显示它。我破坏元素是错的吗?

app.directive('similar', function($rootScope, $compile, $templateCache, Item, Allo){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            var unqId = _.uniqueId('similar');
            elem.on('click', function(){
                // if user closes the list of similar items, destroy the contents
                if (elem.hasClass('glyphicon-upload')) {
                    elem.removeClass('glyphicon-upload');
                    angular.element('.'+ unqId).remove();
                    return;
                }
                elem.addClass('glyphicon-upload');
                var itemId = scope.$parent.item.id;
                var similars = scope.similars[itemId];
                if (similars) {
                    var row = $templateCache.get('inventory/views/_row.htm');
                    var html = $compile('<tr class="'+ unqId +'" ng-repeat="item in category.items('+ similars +') | orderBy:''sort_order''">'+ row +'</tr>')(scope);
                    elem.parents('tr').after(html);
                }
            });
        }
    };
});

首先,这种DOM操作在指令中通常是不必要的。你很有可能实现你想要的东西,如:

<table similar ng-hide="similar_items.length == 0">
  <tr ng-repeat="item in similar_items" ...>
   <!-- contents of inventory/views/_row.htm here -->      
  </tr>
</table>

table将被隐藏,当similar_items同样为空时,<tr>的集合为空,因此您需要在作用域中设置:

elem.on('click', function() {
   ...
   var itemId = scope.$parent.item.id;
   var similars = scope.similars[itemId];   
   scope.similar_items = category.items(similars);
});

你根本不需要手动操作DOM——angular将绑定到作用域中的similar_items属性,并在<tr>上做正确的事情。您可以通过类似的机制添加/删除glyphicon-upload类,尽管隐藏元素上的类的用途将作为练习:)

可能修复你的遗留注释问题;我在不同的情况下遇到过同样的问题(在动画完成后修改作用域的模型),但尚未解决它。