Angular ng-click not working with $compile
Asked Answered
O

1

5

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!');
        };
    }
}
})
Octo answered 10/12, 2015 at 2:28 Comment(0)
L
7

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>
Lipography answered 10/12, 2015 at 9:3 Comment(1)
If you read the usage documentation for $compile, you'll see it accepts a string. docs.angularjs.org/api/ng/service/$compile#usageJess

© 2022 - 2024 — McMap. All rights reserved.