gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:01:55 25 4
gpt4 key购买 nike

在我的 Angularjs 项目中,我遇到了指令嵌套和变量传递的问题。

我做了一个指令头:

.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;
}
}
}
}

在模板中,使用另一个指令:

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

和投票指令:

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

在 votable.html 中:

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

当我运行它时,投票图标应该被隐藏才能开始,但它正在显示。

我有另一个元素+指令组合:

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

该指令在开始时是隐藏的,但展开后,即使切换 showDescriptions 变量也无法折叠。

我是否需要做一些特殊的事情来将变量从指令范围传递到子指令范围?

最佳答案

对于嵌套指令,子指令将在运行父指令的link 函数之前绑定(bind)其数据。如果您需要在父范围内提供一些值以便子指令正确呈现,则需要将其绑定(bind)到父指令的 preLink 中。添加一个编译函数,使其返回您的 preLink 函数,它应该没问题,如下所示:

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

关于javascript - Angularjs 指令将变量传递给子指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21475251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com