【发布时间】:2014-08-12 14:12:15
【问题描述】:
我最近在阅读 John Papa 的固执己见的 AngularJS style guide 并注意到他关于控制器的约定:
/* recommended */
function Customer () {
var vm = this;
vm.name = {};
vm.sendMessage = function () { };
}
当它在控制器中使用时,它工作得很好,因为你可以做这样的事情(他的例子):
<!-- recommended -->
<div ng-controller="Customer as customer">
{{ customer.name }}
</div>
但是,我对它如何与依赖此控制器的指令一起工作感到更加好奇。例如,在我的控制器上使用$scope,我可以这样做:
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";
}
所以我的问题是, 这在指令中如何工作?我试过使用:
{{customer}}
{{this.customer}}
{{exampleCtrl.customer}}
没有任何工作。如您所见,我在黑暗中拍摄,并没有真正理解差异以及如何在 Angular 中使用 this 而不是 scope。此外,由于这不是惯例,我无法找到很多与它相关的资源,因为它比 Angular 更能理解 JS。
感谢任何帮助!
【问题讨论】:
标签: javascript angularjs angularjs-scope