How can I test an AngularJS service from the console?

前端 未结 4 1337
滥情空心
滥情空心 2020-11-29 14:06

I have a service like:

angular.module(\'app\').factory(\'ExampleService\', function(){
  this.f1 = function(world){
    return \'Hello \'+world;
  }
  return         


        
4条回答
  •  自闭症患者
    2020-11-29 15:03

    TLDR: In one line the command you are looking for:

    angular.element(document.body).injector().get('serviceName')
    

    Deep dive

    AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

    To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

    From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

    More information on that in this answer: Can't retrieve the injector from angular
    And even more here: Call AngularJS from legacy code


    Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
    angular.element($0).scope()

提交回复
热议问题