从指令中的编译函数访问控制器

时间:2017-01-18 06:50:56

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-controlleras

我已经搜遍过,我唯一能想到的就是我不明白编译函数的工作原理。

这就是我所拥有的

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>'
  }
});

显示:数据:,似乎没有看到“someValue”变量。 但是,当我使用scope而不是controllerAs语法时,它可以工作。

//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>'
  }
});

显示:数据:23

我在这里缺少什么吗?我甚至正确使用编译? 手册似乎不那么有用了。

1 个答案:

答案 0 :(得分:2)

因为有拼写错误。它是controllerAs,而不是contollerAs

建议使用template function代替compile。这样可以在以后更轻松地升级到组件,也可以避免出现问题 - 如果没有虚拟compile模板,上面指令中的<h1>test</h1>将无法正常工作。