当使用$compiled时,在循环中重复重复项

ng-repeat duplicate itens in the loop when $compiled is used

本文关键字:循环 compiled      更新时间:2023-09-26

我试图加载一些内容到一个引导的弹出窗口。该内容是隐藏div的html元素,其中包括在对象列表下迭代的ng-repeat。好的,它是有效的。但是ng-click在弹窗中不起作用。为了解决,根据我在stackoverflow中阅读的内容,当我将内容设置为弹出窗口时,我使用了$compile选项。是的,它也有用。然而,当我这样做的时候,对象列表显示了它内部的副本。谁能告诉我哪里不对吗?

砰砰作响

angular.module("app", [])
    .controller("progressBarCtrl", function($scope, $timeout, $compile) {
        $scope.value = 90;
		
		$scope.cursos = [
			{ "nome": "Medicina", "percentual": "20" },
			{ "nome": "Ciência da computação", "percentual": "90" }
			
		];		
	
		$scope.showPopover = function() {
			$("#main").popover("show");			
		}
		
 		$timeout(function() {	
			$scope.$apply(function() {		
			$("#main").popover({
				container: 'body',
				html: true,
				content: function () {
					return $compile($("#popper-content").html())($scope);							
				}
			});	
			});
		});
		
		$scope.showAlert = function() {
			alert();
		};
		
    });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="app" ng-controller="progressBarCtrl">
<div class="row">
  <div class="col-md-3 col-md-offset-3" id="main" data-ng-mouseenter="showPopover()" data-placement="bottom" title="Progresso detalhado">
  		<h4>Progresso geral:</h4>
        <div class="progress">
          <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="100" style="width: {{value}}%">
          {{value}}%
          </div>
        </div>
  </div>
</div>
<div id="popper-content" class="hide"  >
    <div data-ng-repeat="curso in cursos">
    	<h3>{{curso.nome}}:</h3>
        <div class="progress">
          <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="{{curso.percentual}}" aria-valuemin="0" aria-valuemax="100" style="width: {{curso.percentual}}%">
          {{curso.percentual}}%
          </div>
        </div>
        
        <div ng-click="showAlert()">click-me</div>       
    </div>
</div>
</body>

这个问题的答案出乎意料地复杂。在幕后,你的重复操作被执行了两次。当应用加载时,因为它位于你应用了Angular控制器的元素(body)内的DIV中。

为了让它正常工作,你不仅需要用CSS"隐藏"模板内容,还需要对Angular隐藏它。您可以通过放置模板和外部文件(到目前为止最常见的事情,以及实际的应用程序)或使用script标记来实现这一点。

同样,在你的示例代码中,你在$timeout中调用了scope apply;这是不必要的,$timeout会为你调用它。

看下面的活塞,我想它现在做你正在寻找的。

http://plnkr.co/edit/jKtG1W1V9a6MZI5uVPdP?p =

预览

最重要的代码位:

    $timeout(function() {   
        $("#main").popover({
            container: 'body',
            html: true,
            content: function () {
                return $compile($templateCache.get('popper-content'))($scope);                          
            }
        });
    });