本文介绍了angular.injector(..)。在控制台中调用不返回单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
脚本:
app = angular.module('app',[])
$ b b app.factory'MyFactory', - >
val:'Clark Kent'
app.controller'MainCtrl',($ scope,MyFactory) - >
MyFactory.val ='Waldo'
$ scope.myFactory = MyFactory
将这个放在控制台中:
angular.injector(['ng','app'])invoke ){console.log(MyFactory);})
...而不是 Waldo
,您将获得 Clark Kent
!!
检查
解决方案
Angular中的服务是单例,
每个注射器一次。
angular.injector
要获取当前的应用程序注入器: angular.element(domElement).injector()
例如:
angular.element(document.querySelector('html'))。inject function(MyFactory){console.log(MyFactory); })
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
解决方案
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); })
这篇关于angular.injector(..)。在控制台中调用不返回单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!