简体   繁体   English

Angularjs指令将变量传递给子指令

[英]Angularjs directive passing variables to sub-directive

In my Angularjs project, I've run into a problem with directive nesting and variable passing. 在我的Angularjs项目中,我遇到了指令嵌套和变量传递的问题。

I made a directive header: 我做了一个指令标题:

.directive('header', [function() {
    return {
        restrict: 'E',
        scope: {},
        templateUrl: 'header.tpl.html',
        link: function(scope, elem, attrs) {
            scope.showDescriptions = false;
            scope.expandDescriptions = function() {
                ...
                scope.showDescriptions = !scope.showDescriptions;
            }
        }
    }
}

And in the template, use another directive: 在模板中,使用另一个指令:

<div class="description" votable show-vote="showDescriptions"></div>

and the votable directive: 和可投票的指令:

.directive('votable', [function() {
    return {
        restrict: 'A',
        scope: {
            showVote: '='
        },
        templateUrl: 'votable.tpl.html',
    }
}

in votable.html: 在votable.html:

<div class="vote" ng-show="showVote"></div>

When I run this, the vote icon should be hidden to start, but it is showing. 当我运行它时,应该隐藏投票图标以启动,但它正在显示。

I have another element + directive combo: 我有另一个元素+指令组合:

<div expandable expand="expandDescriptions" ng-show="showDescriptions"></div>

This directive is hidden at the start, but after expanding, it cannot collapse even though it's toggling the showDescriptions variable. 该指令在开始时隐藏,但在扩展后,即使它切换showDescriptions变量也无法折叠。

Do I need to do something special to pass a variable from the scope of a directive into the scope of a sub-directive? 我是否需要做一些特殊的事情来将变量从指令范围传递到子指令的范围内?

With nested directives, the child directive will have its data bound before the link function for the parent directive is run. 使用嵌套指令,子指令将在运行父指令的链接函数之前绑定其数据。 If you need to have some value in the parent scope available in order for the child directive to render properly, you need to bind that in the preLink of the parent directive. 如果您需要在父作用域中有一些值,以便正确呈现子指令,则需要在父指令的preLink中绑定它。 Add a compile function such that it returns your preLink function, and it should be fine, like so: 添加一个编译函数,使它返回你的preLink函数,它应该没问题,如下所示:

compile: function() {
    return {
        pre: function preLink(scope, elem, attrs) {
            scope.showDescriptions = false;
            scope.expandDescriptions = function() {
            ...
            scope.showDescriptions = !scope.showDescriptions;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM