I want to share so functions across my app, for which I have few factories. The issue is I have to add all these factories in every controller whenever required. With increasing number of factories & controllers this is tedious task!
Thus I was trying to find a way to reduce this redundancy. In browsing SO for same, I came across following question:
Can I make a function available in every controller in angular?
This is what I am looking for, And the below answer look most suitable for me:
https://stackoverflow.com/a/24714658/3375368
Now I want to go one step ahead by removing need of inserting $rootScope
!
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', '$rootScope', function($scope, $rootScope){
appData.foo() //This wont work
$rootScope.appDate.foo() //This will work
//Is there a way to remove dependancy on $rootScope??
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
<!-- This works, but I wont be using this, its from original post -->
</body>
</html>
Another question is whether this approach is good? & how it will affect the working of factory data sharing, i.e. are there any pitfalls?