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

时间:2013-08-26 03:27:53

标签: javascript angularjs

我有两个指令。父母和孩子。我想将一个变量传递给父指令,并让多个子节点可以访问它。以下是指令:

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>

child指令似乎没有得到变量。为什么不呢?

1 个答案:

答案 0 :(得分:4)

首先,“需要”父控制器的正确语法是:

require:"^supNavDirective"

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

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