2014-06-10 153 views
0

以下代码不起作用。显然,我不能从child-dir访问someFunction()AngularJS:从子指令访问父范围

这是从儿童指令访问父范围的问题吗?如何做到这一点,当孩子的指令来自外部库?

角/ HTML:

<parent-dir ng-controller="parentCtrl"> 
    <child-dir ng-click="someFunction()"> 
    </child-dir> 
</parent-dir> 

JS:

.controller('parentCtrl', function($scope) { 
    $scope.someFunction = function() { 
    console.log('hello'); 
    } 
} 

回答

1

的问题是,你的child-dir创造了一个孤立的范围从parent-dir

在您的指令声明中,如果指定范围等于true,则您将有权访问父范围。你会这样做:

directive("child-dir", [ 
    function() { 
     return { 
      restrict: 'A', 
      scope: true, 
      link: function(scope, elem, attrs){ 
        } 
      }; 
     } 
]); 
2

你需要在这里提供你的指令。很可能你正在使用一个隔离作用域来打破作用域的父子链。我的猜测是,你有这样的事情:

angular.module('module').directive('childDir', [function() { 
    return { 
    scope: { 
     // Having scope defined as an object makes it an 'isolate' scope 
     // and breaks the chain between this scope and the parent scope. 
    } 
    }; 
}]; 

为了解决这个问题,你可以访问父控制器直接像这样:

angular.module('module').directive('childDir', [function() { 
    return { 
    require: '^parentCtrl', 
    link: function ($scope, $element, $attrs, parentCtrl) { 
     $scope.someFunction = parentCtrl.someFunction; // of course this only works if you make someFunction a public function on the parentCtrl 
    }, 
    scope: { 
     // Having scope defined as an object makes it an 'isolate' scope 
     // and breaks the chain between this scope and the parent scope. 
    } 
    }; 
}]; 

或者,您可以通过不使你的范围不分离在你的指令定义中返回一个'范围'键或者将它设置为{scope:true}(这会给你一个新的子范围)。另一种选择是通过直接访问父范围(而不是依赖原型继承)来打破孤立障碍,如下所示:$ scope。$ parent.someFunction()。