2

我有兩個指令,其中之一廣播消息得到另外一個是這樣的:(demo

angular.module('app', []); 
angular.module('app').directive('foo', 
    function($rootScope) { 
     return { 
     restrict: 'EAC', 
     link: function($scope, element, attrs, controller) { 
      $rootScope.$on("onStart", function(e,d){ 
       alert(d.message) 
      }); 
     } 
     }; 
    } 
); 
angular.module('app').directive('bar', 
    function($rootScope) { 
     return { 
     restrict: 'EAC',  
     link: function($scope, element, attrs, controller) { 
        $rootScope.$broadcast("onStart", {message: "start"}); 
     } 
     }; 
    } 
); 

這GIEVES消息。

但我需要我的指令模板網址,並設置它像這樣(demo)。

angular.module('app').directive('foo', 
    function($rootScope) { 
     return { 
     restrict: 'EAC', 
     templateUrl: "tpl.html", 
     link: function($scope, element, attrs, controller) { 
      $rootScope.$on("onStart", function(e,d){ 
       alert(d.message) 
      }); 
     } 
     }; 
    } 
); 

但它現在不填充警報。

回答

0

對於要執行的link函數,Angular需要該模板。但是現在模板是異步加載的。因此,您的消息在第一個指令中的鏈接函數被執行之前廣播,因此在創建rootScope中的偵聽器之前進行廣播。

+0

是有這個問題的任何解決方案? – barteloma

+0

這對我來說似乎是錯誤的,但是你可以在'foo'指令的return語句之前放置'onStart'監聽器的註冊。它可以工作,但是非常黑客,而且它不能讓你訪問角度傳遞給'link'函數的所有參數。 – gerrit

0

一個解決辦法是使用的template代替templateUrl

template: "<div>Content of the template.</div>" 

EXAMPLE

+0

但模板的內容非常長。指令控制器在鏈接功能前工作。但它不會填充。 – barteloma