2014-10-28 71 views
0

我有兩個angularjs指令(extWindow和taskBar),並且想要將taskBar的控制器注入extWindow以訪問它的作用域。因爲它們不共享我使用的相同範圍AngularJS - 無法在另一個指令中訪問指令控制器

require : '^$directive' 

語法包含它。 這樣做,我可以擺脫'指令'extWindow'所需的錯誤「控制器'taskBar',找不到'!但TaskBarCtrl在extWindow指令的鏈接(..)方法中仍未定義。

任何建議如何解決它?

var mod = angular.module('ui', []) 
.directive('taskBar', function() { 

    var link = function(scope, el, attrs) { 
     $(el).css('display', 'block'); 
     $(scope.titles).each(function(i,t) { 
      el.append('<span>' + t + '</span>') 
     }); 
    }; 

    return { 
     scope: {}, 
     restrict : 'E', 
     controller: function($scope, $element, $attrs) { 

      $scope.titles = []; 

      this.addTitle = function(title) {    
       $scope.titles.push(w); 
      }; 

      this.removeTitle = function(title) { 
       $scope.titles = jQuery.grep(function(n,i) { 
        return title != n; 
       }); 
      } 
     }, 
     link: link 
    }; 
}).directive('extWindow', function() { 

    return { 
     scope: {}, 
     require: '^?taskBar', 
     restrict: 'E', 
     transclude: true, 
     template: '<div class="ui-window">\ 
      <div class="ui-window-header"><span>{{windowTitle}}</span><div class="ui-window-close" ng-click="close()">X</div></div>\ 
      <div class="ui-window-content" ng-transclude></div>\ 
      </div>', 
     link: function(scope, element, attrs, taskBarCtrl) { 
      scope.windowTitle = attrs['windowTitle']; 
      scope.close = function() { 
       $(element).css('display', 'none'); 
      } 
      //taskBarCtrl is not recognized!!! 
      taskBarCtrl.addTitle(scope.windowTitle); 
     } 
    } 
}); 

http://jsfiddle.net/wa9fs2nm/

謝謝。 golbie。

+0

當您使用的^符號需要,是不是有效說taskBar指令必須是extWindow的父級?我已經提出了很多像這樣的指令,沒有任何問題。你需要透過父指令來使它工作。 – natwallbank 2014-10-28 23:25:02

回答

1

如果你的父指令有一個控制器,並且你需要類似的東西。

this.scope = $scope; 
this.attrs = $attrs; 

而在你在你的子鏈接功能,你需要像

var Ctrl = ctrl || scope.$parent.tBarCtrl; 

這裏有一個Plunker

+0

嗨迪倫,謝謝你這個美麗而實用的例子,但我認爲它需要討論。讓我解釋我的發現。 – KGolbang 2014-10-29 11:48:02

+0

我需要的第一件事就是在模塊中定義一個控制器。然後這個指令就可以看到(至少對於那些在相同範圍內定義的)並且可以被控制器引用:'ctrl'。現在第二個指令想要通過使用require:'^?directivename'來使用另一個指令的控制器。引用它也應該使鏈接函數中的控制器可用。但是控制器在「黃色」指令內不可用。另一方面,「紅色」可以訪問控制器,但是沒有將改變填充到模板中.Thx.http://plnkr.co/edit/HOCi2QlFMA0P77w0OPWL – KGolbang 2014-10-29 12:03:55

+0

我終於管理了正確的解決方案。錯誤的是第二個指令沒有被第一個指令包裝。正如api文檔中所述,'^?name'正在尋找父級別的指令。由於這兩個指令都是兄弟,指令沒有找到,因此taskBarCtrl是未定義的。指令之間通信的另一種解決方案可能是將控制器的外部功能傳遞給它們(&運算符)。看到這個解決方案http://plnkr.co/edit/itEhaA5cfRpxylf6TMZ4?p=preview。 – KGolbang 2014-10-29 20:35:17

相關問題