2013-05-30 184 views
0

从指令中定义的控制器访问范围变量的正确方法是什么?从指令控制器访问范围

例如,我想让父指令的控制器上的click事件调用函数。在父指令中,我希望控制器能够访问“常量”,FOO_VIEW,BAR_VIEW,BAM_VIEW

将这些常量放在顶层控制器中,在这种情况下,SearchCtrl(未显示) ?

指令:

.directive('usersAndApps', function() { 
     return { 
      restrict:'EA', 
      scope: true, 
      controller: function() { 
       this.toggleView = function(viewName){ 
        console.log('show view ' + viewName); 
       } 
      }, 
      link:function(scope, elem, attrs) { 
       scope.FOO_VIEW = 'fooView'; 
       scope.BAR_VIEW = 'barView'; 
       scope.BAM_VIEW = 'bamView'; 
      } 
     } 
    }).directive('usersAndAppsNav', function() { 
     return { 
      restrict: 'AE', 
      require:'^?usersAndApps', 
      replace:true, 
      scope:true, 
      link:function(scope,elem,attrs,usersAndAppsCtrl){ 
       scope.toggleView = function(viewName){ 
        usersAndAppsCtrl.toggleView(viewName); 
       } 
      }, 
      templateUrl:'partials/usersAndApps/throwmeaway' 
     } 
    }); 

模板:

<div> 
    <button class="btn btn-large btn-primary" ng-click="toggleView(FOO_VIEW)">Foo View</button> 
    <button class="btn btn-large btn-primary" ng-click="toggleView(BAR_VIEW)">Bar View</button> 
    <button class="btn btn-large btn-primary" ng-click="toggleView(BAM_VIEW)">Bam View</button> 
</div> 

指令和嵌套(子)指令:

<div ng-controller="SearchCtrl"> 
    <users-and-apps> 
     <users-and-apps-nav></users-and-apps-nav> 
    </users-and-apps> 
</div> 

回答

1

你有什么是好的,但因为你没有在usersAndAppsNav使用分离或transcluded范围,你不需要定义上usersAndApps —控制器API,你可以简单地采取的prototypal scope inheritance优势,如果你访问方法toggleViewParent定义它与相关联usersAndApps范围:

.directive('usersAndApps', function() { 
return { 
    restrict:'EA', 
    scope: true, 
    link:function(scope, elem, attrs) { 
     scope.FOO_VIEW = 'fooView'; 
     ... 
     scope.toggleViewParent = function(viewName){ 
      console.log('show view ' + viewName); 
     } 
    } 
} 
}).directive('usersAndAppsNav', function() { 
return { 
    restrict: 'AE', 
    replace:true, 
    scope:true, 
    link:function(scope,elem,attrs) { 
     scope.toggleView = function(viewName){ 
      scope.toggleViewParent(viewName); 
     } 
    }, 
    templateUrl: ... 
} 
}); 

Fiddle

enter image description here

需要注意的是,当你在你的模板—唯一原因FOO_VIEW的计算结果为fooViewng-click="toggleView(FOO_VIEW)"已经用上了原型继承的是因为原型继承— FOO_VIEW对与usersAndApps相关的范围定义(范围004),子范围(范围005)通过继承链/查找(即,在虚线后面)找到。

-3

看一看覆盖这个话题这个快速的视频教程@http://www.egghead.io/video/LJmZaxuxlRc

他还有一些其他非常棒的AngularJS教程视频链接到该网站。

+0

这些都是很棒的视频,你说得对。我正在寻找一些更具体的东西,特别是因为这个特定的问题涉及操纵DOM,应该在指令级完成。 – binarygiant

+0

我链接到的视频讲述了调用控制器方法的指令 - 是不是你所问的?他有关于指令 - >指令通信的另一个视频@ http://www.egghead.io/video/rzMrBIVuxgM –

+0

不是我正在寻找的。我更感兴趣的是与指令的控制器交谈的指令(作为其他指令的API公开,通过require:'^?myDirective)与它交谈。请参阅上面的代码片段。再次感谢您的建议。我实际上正在研究一些事情,并且在某个时候我会有足够的信息来回答这个问题(在egghead视频之类的帮助下)。再次感谢! – binarygiant

相关问题