William William - 3 months ago 53
AngularJS Question

JQuery selector not working on Angular ng-include

I was testing ng-include in an angular application with JQuery, and I could not fire an event from JQuery on HTML content loaded from ng-include.

In this example, the page has two panels with two click events, the painel1 that is on index.html page and the painel2 that is on contentPanel.html that is being included via ng-include, althought the click event on panel2 from contentPanel.html is not working.

Here is the 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>


Here is the file contentPanel.html that I am including on ng-include:

<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body" id="painel2">
Panel 2, click here!
</div>
</div>
</div>

Answer

You can bind a jQuery click event to the document itself and then the DOM creation cycle with ng-include won't break the binding:

$(document).on("click", "#painel2", function() {
    alert('Você clicou em um painel!');
});

I got the answer from here: jQuery click events not firing within AngularJS templates

Comments