Search code examples
javascriptjqueryangularjsangularjs-controller

angularjs ng-click not working on dynamic html elements


For some reason when using this function('testclickfn') as ng-click on dynamic elements, it doesn't invoke the function. Here is the angularjs file:

app.controller('testctrl',function($scope){
     testfn($scope);

     $scope.showelements = function(){
        displayTestRows();
     }
});

function testfn($scope){
   $scope.testclickfn = function(){
     alert('testing click fn');
   };
}

function displayTestRows(){
   for(var i=0; i < 5; i++){
      $("#testdiv").append('<p ng-click="testclickfn()">click me</p><br>'); 
   }
}

HTML page that calls angularjs controller 'testctrl':

<div id="testdiv" ng-controller="testctrl">
   <button ng-click="showelements()">Show dynamic elements</button><br>
</div>

I'm assuming since the 'click me' tags are being generated after angular has loaded the page, it doesn't know of anything after page is generated so ng-click="testclickfn()" doesn't get registered with angularjs.

How do I get around this situation?


Solution

  • You're creating elements in a way angular has no idea about (pretty bad practice), but not to worry, you can let angular know!

    Change the controller signature to

    controller('testctrl', function($scope, $compile) {
    

    Then run compile the new elements manually to get the ng-click directive activated

    $scope.showelements = function(){
        displayTestRows();
        $compile($("#testdiv").contents())($scope);
    }
    

    If you cant tell, having to use jquery selectors inside your controller is bad, you should be using a directive and the link function to attach the element to the scope (ie, what if you have multiple testctrl elements?), but this'll get you running