0

adding the following 'hyperlink' to html like:

<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>

and then use this code to trigger click event like

 $scope.ClickMe = function () { alert("clicked"); }

works fine, but this did not work when 'hyperlink' generated dynamically like

 $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");

Could anyone explain why did that happen?

Saif
  • 2,611
  • 3
  • 17
  • 37
  • you shouldn't use jQuery to modify the DOM with an angular component. jQuery doesn't update angular, so angular doesn't know there is a new binding to monitor. – Claies Mar 29 '17 at 17:29
  • 2
    you need to compile your code before rendering... [Please refer this](http://stackoverflow.com/questions/19267979/ng-click-not-working-from-dynamically-generated-html) – gopigoppu Mar 29 '17 at 17:30
  • Add script where u adding this html .Using jQuery is not recommended,Use directive and jQlite for it – RIYAJ KHAN Mar 29 '17 at 18:38

4 Answers4

0

Angular processes the bindings on load. Since the element is generated dynamically, you will have to bind it dynamically as well.

Steve Harris
  • 306
  • 2
  • 4
0

If you are in a controller: You're going to want to use the $compile service.

var el =  $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");

$compile(el)($scope);

don't forget to inject $compile into your controller.

However as pointed out in the comments, there are better alternatives than using jquery to manipulate the dom.

Sean Martz
  • 33
  • 6
  • that's assuming this is done in a controller; based on the fact that they are using jQuery to modify the DOM, it's likely this is happening somewhere that angular has no control over. – Claies Mar 29 '17 at 17:31
  • no, it really isn't. They may be trying to modify an element that is under angular's control, but there is no indication that this code is in a controller or not. Besides the fact that if this were inside a controller, there are better ways to manipulate the DOM than to dropping to jQuery. – Claies Mar 29 '17 at 17:35
  • I don't think it's safe to assume anything from 1 line of Angular, 1 line of jQuery, and 1 line of HTML. – itamar Mar 29 '17 at 18:22
0

The problem is when you are using JQuery you haven't compiled it in a DOM.

You have to use $compile which Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

Means $compile compiles the new DOM and link it to the current scope.

Please refer to the AngularJs Docs for more detail.

AP.
  • 8,082
  • 2
  • 24
  • 33
-1

use javascript:void(0) within your hyperlink