我有一个名为'player'的服务,我需要在flash对象加载完成后更新服务。
mySongPlayer.factory('player', function() {
var isPlayerLoaded = false;
var playerHolder = '';
window.playerReady = function(thePlayer) {
playerHolder = window.document[thePlayer.id];
addListeners();
isPlayerLoaded = true;
}
var flashvars = {
file:"",
autostart:"true",
skin: "/skins/glow/glow.zip",
}
var params = {
allowfullscreen:"false",
allowscriptaccess:"always"
}
var attributes = {
id:"player1",
name:"player1"
}
swfobject.embedSWF("/player.swf", "player_placeholder", "100%", "40", "9.0.115", false, flashvars, params, attributes);
var playObj;
return playObj || (playObj = {
currentId: 'test', currentUrl: 'url', playerHolder: ''
});
});
我知道如何使用
访问服务angular.element(DOMElement).injector().get('player')
但是当我需要更新已在模块中创建的实例时,它会返回'player'的新实例。有没有办法做到这一点?我只想要一个播放器实例,但我需要从外部javascript初始化它。
答案 0 :(得分:50)
好吧,我无法真正看到你正在做的所有事情,但你可能只有1/2左右。
Here is a working plunk of what I'm about to describe
injector.get()
应该返回与您应用中的内容相同的服务实例。您可能只是看到一个问题,使您认为您有不同的实例。
所以你需要做的是:
angular.element(DOMElement).scope()
从您的角度元素中删除范围,然后在其上调用$apply()
。以下是代码:
app.controller('MainCtrl', function($scope, myService) {
// Set a var on the scope to an object reference of the
// (or from the) service.
$scope.myService = myService;
});
app.factory('myService', function(){
return {
foo: 'bar'
};
});
//do a little something to change the service externally.
setTimeout(function(){
//get your angular element
var elem = angular.element(document.querySelector('[ng-controller]'));
//get the injector.
var injector = elem.injector();
//get the service.
var myService = injector.get('myService');
//update the service.
myService.foo = 'test';
//apply the changes to the scope.
elem.scope().$apply();
}, 2000)
其他想法:
$window
注入服务,而不是使用窗口对象,以维护服务的可测试性。