angular.injector(..).invoke in the console not ret

2019-06-13 21:03发布

问题:

The script:

app = angular.module('app', [])

app.factory 'MyFactory', ->
  val: 'Clark Kent'

app.controller 'MainCtrl', ($scope, MyFactory) ->
  MyFactory.val = 'Waldo'
  $scope.myFactory = MyFactory

Put this in the console:

angular.injector(['ng','app']).invoke(function(MyFactory) { console.log(MyFactory); })

... and instead of Waldo, you get Clark Kent !!

Why doesn't it return the same object?

Check out the plunkr

回答1:

Services in Angular are singletons in the sense that they are only created once per injector.

angular.injector however creates a new injector function.

To get the current app injector: angular.element(domElement).injector()

For your example:

angular.element(document.querySelector('html')).injector().invoke(function(MyFactory) { console.log(MyFactory); })