使用"本"代替"范围"与AngularJS控制器和指令 [英] Using "this" instead of "scope" with AngularJS controllers and directives
问题描述
我最近读约翰爸爸的自以为是 AngularJS风格指南,发现他的约定控制器上的:
I was recently reading John Papa's opinionated AngularJS style guide and noticed his convention on controllers:
/* recommended */
function Customer () {
var vm = this;
vm.name = {};
vm.sendMessage = function () { };
}
当这是在控制器中使用它工作得很好,你可以做这样的事情(他的例子):
When this is used in a controller it works just fine as you can do something like this (his example):
<!-- recommended -->
<div ng-controller="Customer as customer">
{{ customer.name }}
</div>
不过我在它如何与依赖此控制器指令工作更加好奇。例如,使用 $范围
我的控制器上,我可以做这样的事情:
However I am more curious in how it works with directives that rely on this controller. For example, using $scope
on my controller I can do something like this:
testModule.directive("example", function(){
return{
template: "Hello {{customer}}",
controller: "exampleCtrl"
}
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl($scope){
$scope.message = "Display this";
}
但这种使用我不能做 this.message
:
testModule.directive("example", function(){
return{
template: "Hello {{customer}}", //Doesn't work!
controller: "exampleCtrl"
}
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl(){
var vm = this;
vm.message = "Display this";
}
所以我的问题是,如何的会的这项工作的指示?我试着用:
So my question is, how would this work in the directive? I've tried using:
{{customer}}
{{this.customer}}
{{exampleCtrl.customer}}
和没有工作。正如你所看到的,我在黑暗中拍摄,并没有真正理解的差异,我怎么可以使用这个
的角度,而不是范围
。此外,由于这不是惯例,我一直没能找到很多资源来说它,因为它超过一个角度理解JS的东西。
And none work. As you can see, I'm shooting in the dark and not really understanding the differences and how I could use this
in Angular instead of scope
. Also, as this isn't the convention, I haven't been able to find many resources speaking to it, since it's more a JS understanding thing than Angular.
任何帮助AP preciated!
Any help is appreciated!
推荐答案
在使用这种风格,指示应在每的 controllerAs 属性=https://docs.angularjs.org/guide/directive>指令文档。
When using this style, directives should use the controllerAs
property in their return object per the Directive documentation.
您指令最终会看起来像:
Your directive would end up looking like:
testModule.directive("example", function() {
return {
template: "Hello {{controller.customer}}",
controller: "exampleCtrl",
controllerAs: "controller"
};
});
这篇关于使用&QUOT;本&QUOT;代替&QUOT;范围&QUOT;与AngularJS控制器和指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!