mr1031011 mr1031011 - 1 year ago 80
AngularJS Question

Injector returns undefined value?

  1. I'm trying to get the service from my legacy code and running into a weird error with
    returning undefined:

    Check this plnkr

  1. Also, I'm trying to set back the new property value back to the service, will that be reflected to the scope without the use of watch?

Thank you very much, any pointer or suggestion is much appreciated.

Answer Source

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