0

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?

2 Answers 2

1

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");
};
Sign up to request clarification or add additional context in comments.

Comments

0

Probably you missed to parse the HTML string using angular.element(htmlString) which is then compiled.

var app = angular.module('stackoverflow', []);

app.controller('MainCtrl', function($scope, $compile, $sce) {

  var searchHTML = '<a href="#" data-ng-click="setMarkerToCenterA()">hello</a>';
  var template = angular.element(searchHTML);
  $compile(template)($scope);

  angular.element(document.querySelector('#container')).append(template);

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

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>

<div  ng-app="stackoverflow" ng-controller="MainCtrl">
  <div id="container"></div>
</div>

Comments

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.