2013-06-03 41 views
5

我剛剛與Angular握手,但是當我嘗試將可重用組件抽象爲單獨的模塊時,傳遞範圍越來越好。如何從完全獨立的模塊控制器調用模塊的控制器功能?

我使用的是這裏發現的Angular Youtube模塊https://github.com/arnaudbreton/angular-youtube,但它很糟糕,所以我不得不使用新功能,即支持YouTube的Events。

首先,這裏從第三方模塊相關的片段(有刪節):

angular.module('youtube', ['ng']) 

    .service('youtubePlayerApi', ['$window', '$rootScope', '$log', function ($window, $rootScope, $log) { 
     var player = $rootScope.$new(true); 

     player.playerContainer = null; 

     player.create = function (attrs) {   
      player.playerId = attrs.id; 
      player.videoId = attrs.videoId; 

      return new YT.Player(this.playerId, { 
       videoId: attrs.videoId, 

       events:{ 
        onStateChange: function(event){ 
         switch(event.data){ 
          case YT.PlayerState.PLAYING: 
           attrs.onEvent() 
           break; 
         } 
        } 
       } 
      }); 
     }; 

     player.load = function(){ 
      this.playerContainer = player.create(); 
     } 

     return player; 
    }]) 

    .directive('youtubePlayer', ['youtubePlayerApi', function (youtubePlayerApi) { 
     return { 
      restrict:'A', 
      scope: { 
       id:'@', 
       videoId:'@', 
       onEvent:'&' 
      }, 
      link: function (scope, element, attrs) { 
       youtubePlayerApi.create(attrs); 
      } 
     }; 
    }]); 

然後還有我自己的模塊:

var myapp = angular.module('myapp', ['youtube']); 

myapp.controller('myAppCtrl', ['$scope', '$rootScope', '$location', '$log', 'youtubePlayerApi', function($scope, $rootScope, $location, $log, youtubePlayerApi) { 

    $scope.showVideo = function(){ 
     $scope.youtubePlayer = youtubePlayerApi.load(); 
    } 

    $scope.myEventHandler = function(){ 
     alert('finished!') 
    } 
}]); 

,關聯的模板:

<div ng-app="myapp" id="ng-app"> 
    <div ng-controller="myAppCtrl"> 
     <div youtube-player id="ytplayer" video-id="0BWD5I6YrIo" on-event="myEventHandler()"></div> 
    </div> 
</div> 

正如你所看到的,我正努力連接的myeventhandler()函數3210與youtubeapi模塊。

我也不確定我是否正確地配置了隔離範圍變量,因爲我只在將範圍值傳遞給模板時纔看到它,而不是像這樣的鏈接函數。

任何指向我要去哪裏錯了?

+0

我還沒有將此代碼拉入測試應用程序並使用它,但對我來說,它看起來像你做的一切正確 - YouTube的東西的代碼看起來很腥。我注意到GitHub上的代碼與此處的代碼不匹配;你可能想嘗試更新angular-youtube代碼。 –

回答

2

隔離範圍變量配置正確。 attrs.onEvent()不起作用,因爲屬性是字符串而不是表達式。儘管如此,該指令可以使用它的分離範圍變量傳遞的事件處理程序服務:

link: function (scope, element, attrs) { 
    // using the isolate scope binding 
    youtubePlayerApi.create(attrs, scope.onEvent); 
} 

然後,您將修改create接受新的參數:

player.create = function (attrs, handler) { 

而且還內create,改變attrs.onEvent()handler()

+0

謝謝你們,我懷疑我幾乎在那裏,這一切都歸結爲處理程序的傳遞範圍。 – xcession

相關問題