Looking to streamline a commonly used function in various controllers within an AngularJS project by creating a service/factory that can be accessed through $rootScope
. The objective is to refactor the existing function:
$scope.twitterRefresh = function(obj) {
try {
var old = document.getElementById('twitterContainer');
old.parentNode.removeChild(old);
}
catch (err) {};
var html = "<div id='twitterContainer'>" + $scope.game[0]['twitterEmbed'] + "</div>";
var elem = $compile(html)($scope);
angular.element(document.getElementById('twitterEmbed')).append(elem);
};
into a combination of a $rootScope
& service
in order to eliminate the need to include the service in each controller. However, the following code is not functioning as expected:
app.factory('twitterRefresh', ['$document', '$compile', '$rootScope',
function(obj,$document, $compile, $rootScope) {
try {
var old = document.getElementById('twitterContainer');
old.parentNode.removeChild(old);
}
catch (err) {};
var html = "<div id='twitterContainer'>" + obj + "</div>";
var scope = $rootScope.$new();
var elem = $compile(html)(scope);
angular.element(document.getElementById('twitterEmbed')).append(elem);
}]);
app.run(function($rootScope, twitterRefresh) {
$rootScope.twitterRefresh= function(obj){
twitterRefresh(obj);
}
});
where the following function is invoked in the controller:
$scope.twitterRefresh = $rootScope.twitterRefresh($scope.game[0]['twitterEmbed']);