我正在使用JQuery在角度应用程序中测试ng-include,并且我无法从JQuery上从 ng-include 加载的HTML内容中触发事件。
在此示例中,页面有两个面板,其中包含两个点击事件,index.html页面上的painel1和通过ng-include包含的contentPanel.html上的painel2,但是在panel2上的click事件来自contentPanel.html无效。
这是index.html:
<!DOCTYPE>
<html>
<head lang="pt-br">
<meta charset="UTF-8">
<title>Teste Javascript</title>
<link rel="stylesheet" href="./assets/lib/bootstrap/dist/css/bootstrap.min.css">
</head>
<body ng-app="app">
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Page One</a></li>
<li><a href="#">Page Two</a></li>
</ul>
</div>
</nav>
<div ng-controller="HomeController">
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body" id="painel1">
{{panel1Text}}
</div>
</div>
</div>
<div ng-include="'app/shared/contentPanel.html'"></div>
</div>
<script src="./assets/lib/jquery/dist/jquery.min.js"></script>
<script src="./assets/lib/angular/angular.min.js"></script>
<script>
angular.module('app', []);
angular.module('app').controller('HomeController', function($scope){
$scope.panel1Text = 'Panel 1, click here!';
$(document).ready(function(){
$('#painel1').on('click', function(){
alert('Você clicou em um painel!');
});
$('#painel2').on('click', function(){
alert('Você clicou em um painel!');
});
});
})
</script>
</body>
</html>
以下是我在ng-include上包含的文件contentPanel.html:
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body" id="painel2">
Panel 2, click here!
</div>
</div>
</div>
答案 0 :(得分:0)
您可以将jQuery click事件绑定到文档本身,然后使用ng-include
的DOM创建周期不会破坏绑定:
$(document).on("click", "#painel2", function() {
alert('Você clicou em um painel!');
});
我从这里得到答案:jQuery click events not firing within AngularJS templates
答案 1 :(得分:0)
一种方法是使用文件{ng-controller='HomeController'
中的contentPanel.html
,然后在contentPanel.html页面中写入控制器名称,然后HTML文件即可读取控制器