$compile() does not fire in custom Angular directives Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of $compile() does not fire in custom Angular directives without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following directive:

angular.module("example_module", [])
.directive("example_directive", function() {
  return {
    compile: function(element) {
      element.html('{{example}}');
      return function($scope) {
        $scope.example = "Hello world";
      };
    }
  };
});

and the following HTML code:

<!DOCTYPE html>
<html ng-app="example_module">
  <head>
    <meta charset="utf-8">
    <title>Example title</title>
    <script src="lib/angular/angular.min.js"></script>
    <script src="js/example.js"></script>
  </head>
  <body>
    <div example_directive></div>
  </body>
</html>

I would expect the directive to compile to Hello world, but it compile to an empty string instead. Where is the error?

I could use template or a link function, but my goal here is to understand how the compile function works.

Answer

This has to do with how angular handles directive names. I’ve changed your example to match angular’s naming conventions and put together a Plunk

angular.module("example_module", [])
.directive("exampleDirective", function() {
  return {
    compile: function(element) {
      element.html('{{example}}');
      return function($scope) {
        $scope.example = "Hello world";
      };
    }
  };
});

<body>
    <div example-directive></div>
</body>
We are here to answer your question about $compile() does not fire in custom Angular directives - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji