0

Sometimes I have utility functions that I want to use globally that don't rely on dependency injection in an angularjs app.

I've wanted to throw them in a .constant(..) but I can't seem to find any documentation advocating this though I do remember someone advising against this. I was thinking something like so

angular.module('myApp', [])
   .constant('myFunction', myFunction);

function myFunction(msg) {
  alert(msg);
}

Other resources though suggest putting them into a factory or $rootScope. (example) The former feels verbose and the latter I have a distaste for.

Is it acceptable in angularjs 1.x best practices to use .constant to store global functions that don't rely on dependency injection?

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
  • It seems a bit odd to put global vars in the constant module. If you don't want to dependency inject just put them in a JS file. – camden_kid Apr 08 '16 at 16:22
  • I do it quite often for configuration data. I've never used a function but it seems to work. Created a fiddle: https://jsfiddle.net/vdb2j4bw/ – Rob Apr 08 '16 at 16:26
  • @camden_kid I think a lot of people share your opinion and that's why it's not commonly done with .constant(..). I'm just not sure why it is odd. Why do you find it kind of odd? – ThinkBonobo Apr 10 '16 at 03:34
  • 1
    @ThinkBonobo I prefer to keep AngularJS code within AngularJS module files and anything else within other JS files, so it would make more sense to me to put global vars in a file on their own. However, I try very hard to avoid global vars and put everything in services, like a Utils service for example. – camden_kid Apr 10 '16 at 13:08
  • @camden_kid yeah I guess having a utilities service would be the best option in the end. – ThinkBonobo Apr 11 '16 at 17:28

0 Answers0