I'm trying to get the service from my legacy code and running into a weird error with injector()
returning undefined:
Check this plnkr
Thank you very much, any pointer or suggestion is much appreciated.
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'));
Also, by the way, instead of using jQuery, another Angular option for doing the above is:
var elem = angular.element(document.querySelector('#myCtr'))
Angular provides an equivalent to $(document ).ready()
called angular.element(document).ready()
which we can use.
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.
Combining the two we get:
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;
});
});
updated plnkr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With