0

I am working on a custom AngularJS directive. How to bind an event to the dynamically generated html which is generated by the directive itself. Upon research I found that we need to use $watch and $compile, but I couldn't get it working. I found this answer relevant to my question. What is the alternative for jQuery ON in AngularJS

Any help is greatly appreciated. Please check this out in plunker

app.directive( 'btn', [ '$sce', function( $sce ){ 
return { 
    restrict: 'E',
    replace: true,
    template: '<div ng-bind-html="buttonHtml"></div>',
    link : function ($scope, element, attrs) {
    $scope.buttonHtml = $sce.trustAsHtml('<button ng-click="showMessage()">Click Me</button>');
    $scope.showMessage = function () {
        alert("You clicked Me");
  }
} }; }]);

Thanks in advance

10
  • Could you post the code you tried already using $watch and $compile, which you couldn't get to work? Commented Aug 26, 2014 at 8:59
  • Could you show what you've got so far, it'd be easier to help you. Commented Aug 26, 2014 at 8:59
  • isn't jqlite is doing that for you? Commented Aug 26, 2014 at 9:01
  • @MichaelBromley Please wait. I will edit my question my question with code samples Commented Aug 26, 2014 at 9:02
  • 1
    @vishnu if you are able to post your code in plnkr.co that would be useful. Commented Aug 26, 2014 at 9:04

1 Answer 1

3

I hope this would do like this way:

app.directive('yourcustomdirective', function(){
  return {
    restrict : "E", //<---E is directive like <customdirective></customdirective>
    replace : true,
    template:"<button>Click me.</button>", // <---dynamically generated button
    link:function(scope, element, attrs){
      element.on('click', function(){ // <-----click event bound 
        alert(scope.greet); // <----alerts the greet in the scope
      });
    }
  };
});

Demo Plunkr.

Demo Plunkr with ng-click.

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

13 Comments

I have an ng-click associated with this button. How to make that ng-click work.
@vishnu do make a function in the scope of controller and access that.
Thanks for your help. I need that doGreet() function also inside the directive not in the controller.
The problem is while using ng-bind-html. The event is not getting triggered for the dynamic content. Please check this out in plunker plnkr.co/edit/D5ll1mjzPVqbHHg2Tqb5
@vishnu you have jqlite available in angularjs you can use this element.find('button').on('click', callback);. Read about jQlite here...!
|

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.