问题
I'm trying to use ControllerAs in a directive with no $scope injection, using this instead, and I'm struggling when scope:true
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.
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';
}
Here is the jsfiddle.
回答1:
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>
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
来源:https://stackoverflow.com/questions/30714062/accessing-parent-controllers-scope-within-a-directive-that-uses-controlleras-and