2013-05-30 180 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

相關問題