【问题标题】:ng-repeat got more and more element when used in ng-transclude and toggled by ng-ifng-repeat 在 ng-transclude 中使用并由 ng-if 切换时得到越来越多的元素
【发布时间】:2016-11-30 13:40:41
【问题描述】:

这是我的完整测试代码:

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
    <script>
            angular.module('app', []).controller('MainController',['$scope', function($scope){
                $scope.model = {
                    showList: false,
                    list:[1,2,3,4]
                }
            }]).directive('withTransclude', function(){
                return {
                    restrict: 'E',
                    replace: true,
                    transclude: true,
                    template:'<div><span>transclude container</span><ng-transclude></ng-transclude></div>',
                    link:function($scope, $element, attr, ctrl, transclude){
                        // i dont want the ng-transclude tag so i replaced it
                        // if comment this expression problem disappear but the ng-transclude tag remains
                        $element.find('ng-transclude').replaceWith(transclude());
                    }
                }
            })
        </script>
  </head>
  <body ng-app='app' ng-controller="MainController">
      <button ng-click='model.showList = !model.showList'>toggle show</button>
      <div ng-if="model.showList">
          <span>shown</span>
          <with-transclude>
              <div>hello</div>
              <ul>
                  <li ng-repeat="number in model.list">{{number}}</li>
              </ul>
          </with-transclude>
      </div>
  </body>

</html>

问题: 使用 ng-transclude 时,我不希望 ng-transclude 标签保留在我的页面中,因此我将其替换为已嵌入的内容,但是当通过单击按钮切换 ng-if 时,越来越多的 ng-repeat 元素被渲染,如果我不更换,没关系。

问题: 为什么会出现这个问题?还有没有其他方法可以删除 ng-transclude 标签,不会出现这个问题。

【问题讨论】:

标签: javascript angularjs ng-repeat angularjs-ng-transclude


【解决方案1】:

变化:

$element.find('ng-transclude').replaceWith(transclude());

收件人:

var transcludeEl = $element.find('ng-transclude')
$element.append(transcludeEl.contents())
transcludeEl.remove();

https://plnkr.co/edit/7zw27ldkGp0zeey5z9QI?p=preview

【讨论】:

    【解决方案2】:

    尝试使用 ng-show 而不是 ng-if.....我在使用 ng-show 时没有看到重复

    <div ng-show="model.showList"> 
    

    CHECK它

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 2015-05-04
      • 2013-01-01
      • 2016-07-16
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多