SoFunction
Updated on 2025-04-08

Detailed explanation of the invalid solution for ng-click in page dynamically generated by angularJS

Today I encountered such a requirement. In the dynamic page I wrote, the AngularJS I wrote was invalid and cannot click to respond to the event. The following code and solution are given

1. First, new the data we want to assign to the page

var html = "<a href='javascript:void(0);' ng-click='test()'></a>" 

2. Use the $compile function to compile the above content

var $html = $compile(html)($scope); 

3. Insert the compiled content into the page

$("body").append($html); 

Finish

The following is the full version

('customersCtrl', function ($scope, $http,$compile) { 
$ = function(){ 
  alert('test'); 
} 
 
// TODO dynamically generates ng-click in html is invalid. Solution $compile is passed in//The following sentence is to write the content on the page. First, assign the content you wrote to htmlvar html = "&lt;a href='javascript:void(0);' ng-click='test()'&gt;&lt;/a&gt;" 
  
 
//Compile with $compile 
var $html = $compile(html)($scope); 
 
 
//Add to the page, or anywhere you want to add.  }); 
$("body").append($html); 

In this way, ng-click can trigger the function.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.