1

I have searched all over and the only thing I can come up with is that I don't understand something fundamental about how the compile function works.

Here is what I have

angular.module("app", [])
.directive("foo", function(){
  return {
    scope: {},
    controller: function() {
      this.someValue = 23;
    },
    contollerAs: "ctrl",
    compile: function(tElem, tAttrs) {
      tElem.html("<h1>Data:  {{ctrl.someValue}}</h1>");
    },
    template: '<h1>test</h1>'
  }
});

This displays: Data: and does not seem to see the "someValue" variable. However when I use scope instead of the controllerAs syntax, it works.

//this works fine
angular.module("app", [])
.directive("foo", function(){
  return {
    scope: {},
    controller: function($scope) {
      $scope.someValue = 23;
    },
    contollerAs: "ctrl",
    compile: function(tElem, tAttrs) {
      tElem.html("<h1>Data:  {{someValue}}</h1>");
    },
    template: '<h1>test</h1>'
  }
});

This displays: Data: 23

Is there something I am missing here? Am I even using compile correctly? Manual seems less then helpful.

MadOgre
  • 501
  • 6
  • 15

1 Answers1

2

Because there is a typo. It is controllerAs, not contollerAs.

It is recommended to use template function instead of compile. This makes upgrading to components easier in future, also saves from problems - compile in the directive above won't work correctly if there's no dummy <h1>test</h1> template.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Wow, completely embarrassed. I can't believe I didn't see that after 2 hours of staring at that piece of code! Could you also explain if possible, what is the purpose of the compile function to begin with. What would it ever be used for if link, controller, and template take care of everything. Is there ever a use case for it? – MadOgre Jan 18 '17 at 09:21
  • 1
    It's a matter of taste and practical concerns. The purpose of `compile` is to modify template and return pre-link and/or post-link function. I believe it was there before `template` function and stays for historical reasons. Usually `template` and `controller` and/or link functions ($onInit and $postLink controller hooks in 1.5+) can do the job. – Estus Flask Jan 18 '17 at 09:49