Accessing parent Controllers scope within a direct

2019-07-07 17:40发布

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条回答
Emotional °昔
2楼-- · 2019-07-07 18:21

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

查看更多
登录 后发表回答