ng-click not working for dynamically inserted html

2019-07-24 05:37发布

问题:

Hi I am using angular js for my php project. I am using ngclick for anchor link which is like this

<a href="http://localhost/mediaads/signup" ng-click="showregister($event)">Don't have an account? Create One</a>    

when clicks on the link i will call method showregister in controller and replace the html by calling http get method.

$http.get(baseUrl+'signup').success(function(res){$(elem).replaceWith(res);})    

res is the html data and again it has ng click in the html

Dynamically got html data has again ng clicks in them. Those ng clicks are not working

Can anyone tell me how to make ngclick work for dynamic elements.

回答1:

HTML that is added dynamically like this must manually be linked with a scope.

To do this inject and use the $compile service:

$http.get(baseUrl + 'signup').success(function(res) {
  $(elem).replaceWith($compile(res)($scope));
});

Demo: http://plnkr.co/edit/E0neYHsVnmHKn7goLqL4?p=preview