William William - 1 year ago 223
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:

<head lang="pt-br">
<meta charset="UTF-8">
<title>Teste Javascript</title>
<link rel="stylesheet" href="./assets/lib/bootstrap/dist/css/bootstrap.min.css">
<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>

<div ng-controller="HomeController">
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body" id="painel1">
<div ng-include="'app/shared/contentPanel.html'"></div>

<script src="./assets/lib/jquery/dist/jquery.min.js"></script>
<script src="./assets/lib/angular/angular.min.js"></script>
angular.module('app', []);

angular.module('app').controller('HomeController', function($scope){
$scope.panel1Text = 'Panel 1, click here!';

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

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

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!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download