我有一个称为“播放器”的服务,并且在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')
但是当我需要更新模块中已经创建的实例时,它将返回“玩家”的新实例。有没有办法做到这一点?我只想要播放器的一个实例,但是我需要从外部javascript对其进行初始化。
好吧,我真的看不到您正在做的所有事情,但是您大概只有1/2处。
这是我要描述的工作总结
injector.get()应该返回与应用程序中的服务相同的Service实例。您可能只是看到一个问题,使您 认为 自己有不同的实例。
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