在使用 ControllerAs 和 scope:true 的指令中访问父控制器范围 [英] Accessing parent Controllers scope within a directive that uses ControllerAs and scope:true

查看:30
本文介绍了在使用 ControllerAs 和 scope:true 的指令中访问父控制器范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在没有 $scope 注入的指令中使用 ControllerAs,而是使用它,当 scope:true 时我很挣扎

当我使用隔离范围时,一切正常,因为我可以使用 bindToController: true,但在这种情况下,我遗漏了一些东西,我不知道是什么.

我有这个代码.如您所见,我试图在我的指令中打印 foo3(来自 MyController)和 foo4(来自 MyDirectiveController).这可以在两个控制器中使用 $scope 注入轻松完成,但是当我尝试使用它时,我不知道我是否可以(以及如何)在我的指令中从 MyController 访问 foo3.

角度.module("应用程序",[]).controller('MyController', MyController).controller('MyDirectiveController', MyController).directive('myDirective', myDirective);功能我的控制器(){var vm = 这个;vm.foo3 = 'foo3';}函数 myDirective() {返回 {限制:'E',范围:真实,控制器:MyDirectiveController,控制器为:'vm',模板:'{{vm.foo3}} - {{vm.foo4}}'}}函数 MyDirectiveController() {var vm = 这个;vm.foo4 = 'foo4';}

这是 jsfiddle.

解决方案

当您像这样实例化 MyController 时,只需使用 controllerAs 语法.

<!-- 注意as vmMy"语法:现在一切都可以通过vmMy"访问.--><div ng-controller="MyController as vmMy"><我的指令></我的指令>

现在无论何时您使用 vmMy. 表示法,它都会访问 MyController 范围内的内容!

所以你的模板现在可以像这样:

template: 'From MyController: {{vmMy.foo}}<br>来自 MyDirective:{{vm.foo2}}'

jsFiddle 更新

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.

<!-- 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

这篇关于在使用 ControllerAs 和 scope:true 的指令中访问父控制器范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆