angular.injector(..).invoke in the console not returning a singleton

ε祈祈猫儿з 提交于 2019-12-23 05:20:17

问题


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); })


来源:https://stackoverflow.com/questions/22969223/angular-injector-invoke-in-the-console-not-returning-a-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!