gpt4 book ai didi

javascript - Angular js将变量从父指令传递给子指令

转载 作者:行者123 更新时间:2023-11-29 18:21:17 25 4
gpt4 key购买 nike

我有两个指令。 parent 和 child 。我想将一个变量传递给 parent 指令并让多个子级可以访问它。以下是指令:

directives.directive('supNavDirective', function () {
return {
restrict: "E", //declare by element
replace: true,
scope: {
navtree: '='
},
controller: function ($scope, $element) {
$scope.returnNavTree=function(){
return $scope.navtree
}
},
link: function (scope, element, attrs) {
}
}
})


directives.directive('collection', function () {
return {
require:"supNavDirective",
restrict: "E", //declare by element
link: function (scope, element, attrs,superDir) {
scope.collection = superDir.returnNavTree()
},
template: "<ul class=\"nav nav-list tree\"><member ng-repeat=\"member in collection\" member=\"member\"></member></ul>"
}
})

这是 html:

<superNavDirective collection navtree="analyticsNavTree"></superNavDirective>

子指令似乎没有获取变量。为什么不呢?

最佳答案

首先,“要求”父 Controller 的正确语法是:

require:"^supNavDirective"

其次,您必须将 returnNavTree 方法添加到 Controller 实例本身(而不是 $scope)以从子指令访问它,如下所示:

...
controller: function ($scope, $element) {
this.returnNavTree = function(){
return $scope.navtree
}
},
...

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

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