我刚刚开始掌握 Angular,但是当我尝试将可重用组件抽象为单独的模块时,传递范围让我变得更好。
我正在使用在https://github.com/arnaudbreton/angular-youtube找到的 Angular Youtube 模块,但它严重不足,所以我正在使用新功能,即支持 youtube API 的事件。
首先,这是第三方模块的相关片段(删节):
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()
功能myAppCtrl
与youtubeapi
模块连接起来。
我也不确定我是否正确配置了 Isolate 范围变量,因为我只在将范围值传递给模板时才看到它完成,而不是像这样的链接函数。
关于我哪里出错的任何指示?