Accessing the scope of parent controllers in the directive that uses controllers and scope: true
I am trying to use ControllerAs in a non-injected $ scope directive using this instead and I am scared when scope: true
When I use the isolated area everything works fine because I can use it bindToController: true
, but in this case I am missing something and I don't know what.
I have this code. As you can see, I am trying to print foo3 (from MyController) and foo4 (from MyDirectiveController) in my directive. This can be done easily using $ scope injection in both controllers, but when I try to use that, I don't know if I can (and how) 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 a jsfiddle .
source to share
Just use the syntax controllerAs
when you create your MyController like this.
<!-- Notice the "as vmMy" syntax : Now everything can be accessed via "vmMy." -->
<div ng-controller="MyController as vmMy">
<my-directive></my-directive>
</div>
Now when you use the notation vmMy.
, it will access things from the MyController scope!
So your template could now be like this:
template: 'From MyController: {{vmMy.foo}}<br> From MyDirective: {{vm.foo2}}'
source to share