问题描述
我想在没有$范围注入指令使用ControllerAs,使用这个,而是和我挣扎的时候范围:真正的
I'm trying to use ControllerAs in a directive with no $scope injection, using this instead, and I'm struggling when scope:true
当我使用一个孤立的范围内的一切工作正常,因为我可以使用 bindToController:真正的
,但在这种情况下,我失去了一些东西和我不知道是什么。
When I use an isolated scope everything works fine because I can use bindToController: true
, but in this case I'm missing something and I don´t know what.
我有这样的code。正如你所看到的,我想在我的指令打印foo3(从myController的)和foo4(从MyDirectiveController)。这可以通过使用$范围注射两个控制器很容易做到,但是当我试图用这个话我不知道如果我能(以及如何)从在myController的指令我访问foo3。
I have this code. As you can see, I'm trying to print foo3 (from MyController) and foo4 (from MyDirectiveController) in my directive. This can be easily done using $scope injection in both controllers, but when I try to use this then I don´t know if I can (and how to) access foo3 from MyController in my directive.
angular
.module("app",[])
.controller('MyController', MyController)
.controller('MyDirectiveController', MyController)
.directive('myDirective', myDirective);
function MyController() {
var vm = this;
vm.foo3 = 'foo3';
}
function myDirective() {
return {
restrict: 'E',
scope: true,
controller: MyDirectiveController,
controllerAs: 'vm',
template: '{{vm.foo3}} - {{vm.foo4}}'
}
}
function MyDirectiveController() {
var vm = this;
vm.foo4 = 'foo4';
}
下面是。
推荐答案
简单,当你实例化你喜欢myController的这样使用 controllerAs
语法。
Simply use the controllerAs
syntax when you instantiate your MyController like so.
<!-- Notice the "as vmMy" syntax : Now everything can be accessed via "vmMy." -->
<div ng-controller="MyController as vmMy">
<my-directive></my-directive>
</div>
现在,只要您使用 vmMy。
标记,它会从myController的的范围内访问的东西!
Now anytime you use vmMy.
notation it'll access things from MyController's scope!
所以你的模板,现在可以像这样:
So your template can now be like so:
template: 'From MyController: {{vmMy.foo}}<br> From MyDirective: {{vm.foo2}}'
jsFiddle update
这篇关于访问使用ControllerAs和范围指令中父控制器范围:真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!