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.

1

1 Answer 1

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.

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

4 Comments

not working ! i guess because your html is static where as my html is dynamic
doesn't work if i pass a object that is binded to the view as a argument to the alert function
cant i compile without using jquery ?
@varunsinghal65 by object means an angular object? yes of course you can. I updated my plnkr again. check it out

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.