0

I might need to investigate why I'm sharing code between Angular and other objects in my page. Fair enough. But in the meantime:

I've got a bit of code that creates IDs. It's in an Angular service:

  angular.module("Gamma.services").service "idService", () -> 
    @newId = ->
      id = String.fromCharCode(Math.floor(Math.random() * 25) + 65) +
      ((@someNumber + Math.floor(Math.random() * 1e15) +
      new Date().getMilliseconds()).toString(36)).toUpperCase()

OK so that's nifty and all, but I need to share this little chunk of code with some non-Angular code in my app. I've got a solution to it (moved this code into a function off of the window object), but I think the more-correct solution might be to pass a function pointer that points to the Angular service.

How can I pass an Angular service to non-Angular code?

jcollum
  • 43,623
  • 55
  • 191
  • 321

1 Answers1

1

Updated per @jcollum's comment/tip

angular.module('myApp', []).
factory('myService', [function() {
  return function() {
      alert('hello from the service')
  };
}]);

angular.element(document).ready(function(){
    angular.bootstrap(document, ['myApp']);
    var doc = angular.element(document),
        injector = doc.injector(),
        myService = injector.get('myService');
    myService(); // alerts
});
Brian Lewis
  • 5,739
  • 1
  • 21
  • 28
  • Yeah I tried that $service call off of the local scope, no bueno: `Object # has no method '$service'`. Considering the age of that google group post I suspect it's just outdated. – jcollum Jul 01 '13 at 20:37
  • 1
    Hey I don't want to steal your karma so have a look at http://stackoverflow.com/a/13614059/30946 and update your answer. Getting the service via the injector works. – jcollum Jul 01 '13 at 20:48
  • Thanks @jcollum. I updated my answer using a similar approach. – Brian Lewis Jul 01 '13 at 20:55