有没有办法从AngularJS中的指令获取外部控制器名称?

时间:2014-02-15 08:03:50

标签: javascript angularjs

我是AngularJS的新手......以下是问题:

例如:

HTML

<div ng-controller='DemoController'>
  <div my-directive></div>
</div>

的JavaScript

app.directive('myDirective', function(){
  return {
    restrict: 'A',
    link: function(scope, element, attrs){
      //I want to get the outer controller name (in this case 'DemoController') here when using this directive
      // var controller_name = ?
    }
  };
});

如何获取外部控制器名称?

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以使用其属性将任何您想要的内容传递给您的指令。请参阅guide about directives。在你的情况下,这样做很好:

HTML

<div ng-controller='DemoController'>
  <div my-directive="DemoController"></div>
</div>

JS

app.directive('myDirective', function(){
  return {
    restrict: 'A',
    link: function(scope, element, attrs){
      var controller_name = attrs.myDirective;
    }
  };
});

答案 1 :(得分:0)

<强> HTML

<div ng-controller='DemoController'>
  <div my-directive></div>
</div>

<强>的JavaScript

app.directive('myDirective', function(){
  return {
    restrict: 'A',
    link: function(scope, element, attrs, controller_name){
      //I want to get the outer controller name (in this case 'DemoController') here when using this directive
      console.log(controller_name);//using this you can get your current controller name
    }
  };
});