0

I am creating a forum where the replies are written with AngularJS (ng-repeat). A reply can contain links, and on all links, I have added a ng-click. This ng-click is not fired.

I guess it is because by the time the link is written to the dom, AngularJS is done hooking up functions. Are there any workarounds?

Here is an example: http://plnkr.co/edit/Jg0jVOpPL1LcVPHe5YQz?p=preview

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $sce) {
    $scope.htmlBody = '<a href="http://www.google.com" ng-click="testmethod()" target="_blank">This does not work</a>';

    $scope.toTrustedHtml = function(htmlCode) {
      return $sce.trustAsHtml(htmlCode);
    };

    $scope.testmethod = function()
    {
       alert('yes');
    }
});


<body ng-controller="MainCtrl">
   <a href="http://www.google.com" ng-click="testmethod()" target="_blank">This works</a>
   <br /><br />
   <p ng-bind-html="toTrustedHtml(htmlBody)"></p>
</body>

Thanks Rasmus

3
  • And your code is? How have you added an ng-click? Commented Sep 18, 2014 at 10:53
  • You need to post some code if you want help, otherwise you'll just get downvotes... ng-click in a repeat should be fine, so you are not using Angular correctly Commented Sep 18, 2014 at 11:09
  • have a look at this answer - stackoverflow.com/questions/22737927/… Commented Sep 18, 2014 at 11:54

1 Answer 1

0

Here is a simple demo for your case: jsfiddle.net/HB7LU/6469/.

The idea is that you need to use $compile to let angular know you are adding dynamic functions.

Sign up to request clarification or add additional context in comments.

7 Comments

I don't add elements with JavaScript. It is a complete bodytext with links in it. Can I do it a similar way?
As I said, the jsfiddle just gave you an idea what to do, not exactly your case. I think you can still use $compile. Give a shot and let us know.
I used the directive that Lee Willis suggested, but this seems to work too. Thanks.
I took a look at that one: stackoverflow.com/questions/22737927/…, it needs to change html and js and it is overly complicated.
All I had to do was to include the directive in my project and use <p compile="htmlBody"></p> instead of <p ng-bind-html="toTrustedHtml(htmlBody)"></p>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.