我到处搜索,唯一能想到的是我不了解有关编译功能如何工作的一些基本知识。
这是我的
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/