【问题标题】:Angular directives with ^require - access parent scope?带有 ^require 的 Angular 指令 - 访问父范围?
【发布时间】:2016-04-08 15:26:50
【问题描述】:

我正在尝试弄清楚如何正确使用带有嵌入和 ^require 的嵌套指令。我想让一个外部指令有一个由嵌套子指令更新的变量,但我希望所有子指令都链接到该变量。我写了一个非常简单的例子来演示这个问题

JS

(function () {
    'use strict';

    angular
        .module('app')
        .directive('test', test);

    function test() {
        var directive = {
            bindToController: true,
            controller: testController,
            'controllerAs': 'testController',
            scope: {},
            templateUrl: 'scripts/test/test.html',
            transclude: true
        };
        return directive;
    }

    function testController() {
        var self = this;
        self.childCount = 0;

        self.addChild = function addChild(child) {
            self.childCount++;
            child.childNumber = self.childCount;
        }
    }

})();


(function () {
    'use strict';

    angular
        .module('app')
        .directive('child', child);

    function child() {
        var directive = {
            'scope': {},
            'link': link,
            'templateUrl': 'scripts/test/child.html',
            'transclude': true,
            'require': '^test'
        };
        return directive;

        function link(scope, element, attrs, testController) {
            scope.childNumber = null;
            testController.addChild(scope);
        }

    }

})();

主要的 HTML 调用

<test>
    <child></child>
    <child></child>
    <child></child>
</test>

test.html 部分

<h1>self.childCount = {{testController.childCount}}</h1>
<div ng-transclude></div>

child.html 部分

<h3>I am child {{childNumber}} out of {{testController.childCount}}</h3>

输出(和问题)

self.childCount = 3
I am child 1 out of 
I am child 2 out of 
I am child 3 out of 

如您所见,child.html 输出不知道如何输出 {{testController.childCount}}。关于出了什么问题的任何想法?

【问题讨论】:

    标签: javascript angularjs angular-directive angularjs-ng-transclude


    【解决方案1】:

    我通常不使用controllerAs 语法,但可以尝试从子范围中删除'scope': {}。可能是通过创建隔离范围,您的子指令无法访问父控制器范围。

    【讨论】:

    • 我明白你的意思史蒂夫,但我试图让子指令有一个隔离范围,这样他们就可以知道他们是“孩子 1 出 X”和“孩子 2 出X”。如果我没有隔离作用域,那么第一个变量(在我的示例中称为 childNumber)将附加到父作用域,因此所有变量都会说“我是 3 个孩子中的 3 个”跨度>
    • 我的想法是 childNumber 字段是子作用域上的一个成员,它继承了原型,因此每个子作用域都会有自己的 childNumber 字段,只要它在子作用域中声明。不过我可能错了。
    猜你喜欢
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多