AngularJS:从子指令访问父作用域

时间:2014-06-10 21:21:17

标签: angularjs angularjs-directive angularjs-scope

以下代码不起作用。显然,我无法从someFunction()访问child-dir

是否从子指令访问父作用域?如果子指令来自外部库,该怎么做?

角/ 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');
  }
}

2 个答案:

答案 0 :(得分: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()。

答案 1 :(得分:1)

问题是您的child-dir已从parent-dir创建了一个独立的范围。

在指令声明中,如果将scope指定为等于true,则可以访问父作用域。你这样做:

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