2

I have a function that adds certain html to my page when called :

function htmlAppend(i)
       {
        dynamicHtml = dynamicHtml + '<div id="list_item_wrapper">' + 
        '<div class="list_item_template" id="list_image_wrapper">' +
        '<img class="list_image_style" ' +
        'src=" ' + jsonData.cars[i].ImgURL  + ' "/>' +
        '</div>' +
        '<div class="list_item_template white_font car_details_wrapper">' +
         jsonData.cars[i].CarName+ '<br>' +
         jsonData.cars[i].Brand  + '<br>' +
         jsonData.cars[i].Model  + '<br>' +
         jsonData.cars[i].FuelType + '<br>' + 
        '<span style="font-size:40px;">' +
        '&#8377; ' + jsonData.cars[i].Price + 
        '</span> <br> ' +
        jsonData.cars[i].Experience +
        '<input type="button" id="buy_now_btn" class="button1" ng-click="alert("hi")">Buy</button>' +
        '</div>' +
        '</div>'
       }

Problem : Now this html is displayed correctly in my page but for some reason when button is clicked ng-click event doesn't fire , when i replaced it with onClick then onClick fires . i am unable to understand why ng-click is not firing , can somebody help ?

Additional Info : htmlAppend is a private function of a service that is called from the controller upon some user input.

varunsinghal65
  • 536
  • 1
  • 5
  • 20
  • 2
    Possible duplicate of [ng-click not working from dynamically generated HTML](http://stackoverflow.com/questions/19267979/ng-click-not-working-from-dynamically-generated-html) – DAXaholic Jul 30 '16 at 11:33

1 Answers1

3

No, you can't just write alert on your ng-click. When you write alert("hi") on your ng-click directive, it automatically goes and look for a method in your controller that is named $scope.alert(). That is why onClick works, because it is just plain old JavaScript, where as ng-click involves scope binding.

In your controller, write this:

  $scope.alert=function(string){
    alert(string);
  };

and you are good to go. Here is the working plnkr.

Edit: did not read carefully that you are dynamically binding it. Updated plnkr.

For this case you will need to compile it:

  var $el = $('<button ng-click=' + 'alert("hello")' + '>I am a button</button>');
  $compile($el)($scope).appendTo('#testing');

where #testing can be any DOM selector you want.

Still the point is to tell you you can't just write alert in ng-click directive.

Added bonus: do not write DOM manipulating logic inside the controller. You may want to use a directive instead.

CozyAzure
  • 8,280
  • 7
  • 34
  • 52