由于 cmets 中的字符限制以及包含部分答案的感觉,将我的评论作为答案发布。
鉴于各种指南和教程建议您不应在控制器中访问 DOM,为什么这甚至可能?
如前所述,人们建议在您的代码中采用特定方法并不要求他们限制您。
是否有任何非骇客的用例?
在大多数情况下,我想不出有什么好处(回复您的评论)。有一次我使用这种方法是实现一个 youtube iframe API 指令。
当有人停止播放器时,必须从 DOM 中删除该元素。
在某处的可用代码中是否有任何使用此示例的示例?
这里有一些代码,虽然它是很久以前的,我已经删除了一些部分并且被认为是 hacky?
angular.module('mainApp.youtube').directive('youtubePlayer', function($window,$element logging, ui,) {
return {
restrict: 'A', // only activate on element attribute
scope: true, // New scope to use but rest inherit proto from parent
compile: function(tElement, tAttrs) {
// Load the Youtube js api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
},
controller: function($scope, $element, $attrs) {
// This is called when the player is loaded from YT
$window.onYouTubeIframeAPIReady = function() {
$scope.player = new YT.Player('player', {
height: '250',
width: '400',
playerVars: {
'autoplay': 0,
'controls': 1,
'autohide': 2
},
//videoId: $scope.live_track.video_id,
events: {
'onReady': $scope.onPlayerReady,
'onStateChange': $scope.onPlayerStateChange,
'onError': $scope.onError
}
});
};
// When the player has been loaded and is ready to play etc
$scope.onPlayerReady = function (event) {
$scope.$apply(function(){
logging.info("Playa is ready");
logging.info($scope.player);
// Lets also broadcast a change state for the others to catch up
player_service.broadcast_change_state({"state": $scope.player.getPlayerState()});
// Should try to just load the track so that the users can press play on the playa
});
};
// When the player has been loaded and is ready to play etc
$scope.onError = function (event) {
$scope.$apply(function(){
logging.info("Playa Encountered and ERROR");
logging.info(event)
});
};
$scope.start_playing = function (jukebox_id){
logging.info('Yes I am starting...');
};
$scope.$on('handleStartPlaying', function(event, jukebox_id) {
console.log('Got the message I ll play');
$scope.start_playing(jukebox_id);
});
$scope.$on('handlePausePlaying', function() {
console.log('Got the message I ll pause');
$scope.player.pauseVideo();
});
$scope.$on('handleResumePlaying', function() {
console.log('Got the message I ll resume');
$scope.player.playVideo();
});
$scope.$on('handleStopPlaying', function() {
console.log('Got the message I ll stop');
$scope.player.stopVideo();
});
$scope.$on('HandleCloseframe', function() {
console.log('Got the message I ll stop');
$scope.player.stopVideo();
//Should destroy obje etc
// Look here
$element.remove(); // blah blah blah
});
},
ink: function(scope, elm, attrs, ctrl) {
}
}
});
请随时纠正我或提供更好的方法。在当时,这似乎是合法的。至少如果我们不犯错误,我们就不会学习。