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.
Simply use the
controllerAs
syntax when you instantiate your MyController like so.Now anytime you use
vmMy.
notation it'll access things from MyController's scope!So your template can now be like so:
jsFiddle update