Blu*_*est 5 javascript angularjs angularjs-scope
我最近正在阅读John Papa舆论的AngularJS风格指南,并注意到他在控制器上的惯例:
/* recommended */
function Customer () {
var vm = this;
vm.name = {};
vm.sendMessage = function () { };
}
Run Code Online (Sandbox Code Playgroud)
当它在控制器中使用时它可以正常工作,因为你可以做这样的事情(他的例子):
<!-- recommended -->
<div ng-controller="Customer as customer">
{{ customer.name }}
</div>
Run Code Online (Sandbox Code Playgroud)
但是我更喜欢它如何与依赖于这个控制器的指令一起工作.例如,$scope在我的控制器上使用我可以这样做:
testModule.directive("example", function(){
return{
template: "Hello {{customer}}",
controller: "exampleCtrl"
}
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl($scope){
$scope.message = "Display this";
}
Run Code Online (Sandbox Code Playgroud)
但我不能这样做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";
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何将这项工作的指示?我尝试过使用:
{{customer}}
{{this.customer}}
{{exampleCtrl.customer}}
Run Code Online (Sandbox Code Playgroud)
没有人工作.正如你所看到的,我在黑暗中拍摄并没有真正理解差异以及我如何this在Angular中使用而不是scope.此外,由于这不是惯例,我无法找到许多与之对话的资源,因为它比Angular更像是一个JS理解的东西.
任何帮助表示赞赏!
kly*_*lyd 11
使用此样式时,指令应controllerAs根据指令文档在其返回对象中使用该属性.
您的指令最终会如下所示:
testModule.directive("example", function() {
return {
template: "Hello {{controller.customer}}",
controller: "exampleCtrl",
controllerAs: "controller"
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2693 次 |
| 最近记录: |