喷油器返回未定义的值? [英] Injector returns undefined value?
问题描述
-
我正在尝试从旧版代码中获取服务,并遇到一个奇怪的错误,其中
injector()
返回未定义:
- 此外,我正在尝试将新的属性值重新设置为服务,是否可以在不使用watch的情况下将其反映到作用域?
非常感谢您,任何指针或建议都将受到赞赏.
Thank you very much, any pointer or suggestion is much appreciated.
推荐答案
您正在尝试在DOM构建之前获取元素.与在$(document ).ready()
外部运行javascript基本上是相同的问题.因此,此行没有要获取的元素:
You're trying to get the element before the DOM has been constructed. It's basically the same issue as running javascript outside of a $(document ).ready()
. So this line has no element to get:
var elem = angular.element($('#myCtr'));
另外,顺便说一句,代替上面的jQuery,另一个用于执行上述操作的Angular选项是:
Also, by the way, instead of using jQuery, another Angular option for doing the above is:
var elem = angular.element(document.querySelector('#myCtr'))
Angular提供了与$(document ).ready()
等效的名称,称为angular.element(document).ready()
,我们可以使用它.
Angular provides an equivalent to $(document ).ready()
called angular.element(document).ready()
which we can use.
但是您还需要获取scope
并在scope.$apply()
内执行更改,以便Angular知道您已更改了应注意的内容.
But you'll also need to grab scope
and execute your change within a scope.$apply()
so that Angular is aware that you've changed something that it should be aware of.
将两者结合起来:
angular.element(document).ready(function () {
var elem = angular.element($('#myCtr'));
//get the injector.
var injector = elem.injector();
scope= elem.scope();
scope.$apply(function() {
injector.get('cartFactory').cart.quantity = 1;
});
});
这篇关于喷油器返回未定义的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!