简体   繁体   English

如何从2级指令访问控制器范围

[英]how to access controller scope from a 2 level directive

I am trying to build generic code as much as possible. 我正在尝试构建尽可能多的通用代码。

So I'm having 2 directives, one nested inside the other while I want the nested directive to call a method on the main controller $scope. 因此,我有2个指令,一个指令嵌套在另一个指令中,而我希望嵌套指令在主控制器$ scope上调用方法。

But instead it requests the method on the parent directive, I want to know how to execute a method against the main controller scope instead of the parent directive. 但是相反,它要求使用父指令上的方法,我想知道如何针对主控制器范围而不是父指令执行方法。

Here is a sample code for my issue My HTML should look something like this: 这是我的问题的示例代码我的HTML看起来应该像这样:

<div ng-controller='mainctrl'>
  <div validator>
    <div datepicker select-event='datepickerSelected()'/>
  </div>
</div>

Javascript: 使用Javascript:

var app = angular.module("app",[]);

var mainctrl = function($scope){
  $scope.datepickerSelected = function(){
    //I WANT TO ACCESS THIS METHOD
  }
}

app.directive("validator",function(){
  return {
    scope : {
      //the datepicker directive requests a datepickerSelected() method on this scope
      //while I want it to access the mainctrl scope
    }
    link: function(scope){
      //some code
    }
  }
});

app.directive("datepicker", function(){
  return{
    scope: {
      selectEvent: '&'
    }
    link: function(scope, elem){
      //example code
      $(elem).click(scope.selectEvent); //want this to access mainctrl instead validator directive
    }
  }
});

Simply remove the validator directive's scope property, thus eliminating its isolated scope. 只需删除验证程序指令的scope属性,从而消除其孤立的范围。 That means that validator will have the same scope that it is nested in (your controller) and datepicker will use that scope. 这意味着验证器将具有与嵌套在您的控制器中的作用域相同的作用域,而datepicker将使用该作用域。

Another option if you want both to have isolated scopes (doesn't sound like you do) is to pass the function through to "validator's" scope. 如果您想要两个都有独立的作用域(听起来并不像您一样),则另一个选择是将函数传递给“验证者”的作用域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM