javascript - 从指令中的编译函数访问 Controller

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

这显示:Data: 并且似乎没有看到“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

我在这里遗漏了什么吗?我什至正确使用编译? 手册似乎没有那么有用。

最佳答案

因为有错别字。是controllerAs , 不是 contollerAs .

推荐使用 template function而不是 compile .这使得将来更容易升级到组件,也可以避免出现问题 - compile如果没有虚拟 <h1>test</h1>,上面的指令将无法正常工作模板。

关于javascript - 从指令中的编译函数访问 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713059/

相关文章:

javascript - 从字符串中获取 url 作为数组

javascript - 使用 php 从组合框插入

javascript - 在 json key 中使用管道符号 (|) 是否错误?

javascript - 如何使用 AngularJS 绑定(bind)到复选框值列表?

javascript - Controller 中的 Angular 函数在 promise 后没有被调用

javascript - 使用 Express 上传图像

angularjs - bootstrap navbar 几个错误

javascript - Angular 获取共享指令的所有元素的列表

javascript - AngularJS:ng-repeat 中的 ng-model setter

javascript - 为什么过滤器隐藏所有元素?