我有两个指令。一位 parent 和一个 child 。我想将一个变量传递给父指令并使其可供多个子指令访问。以下是指令:
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/