Attempting to consolidate a function used across multiple controllers in an AngularJS project to a service/factory that I can call using $rootScope. The goal is to change the following 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 to avoid having to include the service in every controller that requires the function. The following code, however, isn't working:
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 called in the controller..
$scope.twitterRefresh = $rootScope.twitterRefresh($scope.game[0]['twitterEmbed']);
$scope.twitterRefresh() = $rootScope.twitterRefresh.... did you mean to put the brackets()in?$scope.twitterRefresh = function() { $rootScope.twitterRefresh($scope.game[0]['twitterEmbed']); }looks more useful to me