gpt4 book ai didi

javascript - 使用 $compiled 时 ng-repeat 循环中的重复项

转载 作者:行者123 更新时间:2023-11-30 16:38:28 25 4
gpt4 key购买 nike

我正在尝试将一些内容加载到 Bootstrap 的弹出窗口中。此内容是隐藏的 div 的 html 元素,除其他外,它具有在对象列表下迭代的 ng-repeat。好的,它有效。但是 ng-click 在弹出框内不起作用。为了解决,根据我在 stackoverflow 中阅读的内容,我在将内容设置为 popover 时使用了 $compile 选项。是的,它也有效。但是,当我这样做时,对象列表在其中重复显示。有人可以告诉我哪里出了问题吗?

Plunker

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 Controller 的元素(主体)内的 DIV 中。

为了使这项工作正常进行,您不仅需要使用 CSS 来“隐藏”模板内容,还需要从 Angular 中隐藏它。您可以通过放置模板和外部文件(到目前为止最常见的东西,也是真实的应用程序)或使用脚本标签来做到这一点。

此外,在您的示例代码中,您在 $timeout 内调用了 scope apply;这不是必需的,$timeout 会为你调用它。

请参阅以下 plunker,我认为它现在可以满足您的需求。

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

最重要的代码:

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

关于javascript - 使用 $compiled 时 ng-repeat 循环中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com