Search code examples
htmlangularjsangularjs-ng-click

$compile not triggering ng-click in angularjs


I am generating dynamic html element from angularjs controller.I have used $compile to make ng-click work inside html element.But still it is not calling the function.

Here is my js

    var accountApp = angular.module('accountApp', ['ngRoute']);
    accountApp.config(['$compileProvider',function($compileProvider )
    .controller('myController',function($scope,$compile) 
    {
      var searchHTML = '<li><a href="javascript:void(0)" data-ng-
      click="setMarkerToCenterA()">'+item.title+'</a></li>';
      $compile(searchHTML)($scope);

      $scope.setMarkerToCenterA = function() {
      alert("this alert is not calling");
    }
   });
  }]);

I have injected the dependencies also.Can anyone tell why ng-click is not calling function even though i am using $compile?


Solution

  • First you need an element where this li element will be located.

    <div ng-controller="myController">
        <ul id="list"></ul>
    </div>
    

    Then in your controller:

    var element = angular.element("#list");
    element.html($compile(html)($scope));
    
    $scope.setMarkerToCenterA = function() {
        alert("Here");
    };