Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-click not working with $compile

I have code similar to the below code to trigger a click event in an Angular app. Why is not the event triggering?

var app = angular.module("myApp", [])

app.directive('myTop',function($compile) {
return {
    restrict: 'E',
    template: '<div></div>',
    replace: true,
    link: function (scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $compile(childElement)(scope);

        scope.clickFunc = function () {
            alert('Hello, world!');
        };
    }
}
})
like image 498
freddy83 Avatar asked Dec 10 '15 02:12

freddy83


1 Answers

Change your compile statement like this:

$compile(element.contents())(scope);

You were passing a DOM string childElement which is really not a DOM element instead it is a string. But the $compile needs the DOM element(s) to actually compile the content.

var app = angular.module("myapp", []);

app.directive('myTop', ['$compile',
  function($compile) {
    return {
      restrict: 'E',
      template: '<div></div>',
      replace: true,
      link: function(scope, element) {
        var childElement = '<button ng-click="clickFunc()">CLICK</button>';
        element.append(childElement);
        $compile(element.contents())(scope);

        scope.clickFunc = function() {
          alert('Hello, world!');
        };
      }
    }
  }
])
<html>

<body ng-app="myapp">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <my-top></my-top>
</body>

</html>
like image 84
Shashank Agrawal Avatar answered Oct 15 '22 17:10

Shashank Agrawal