Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injector returns undefined value?

Tags:

angularjs

  1. I'm trying to get the service from my legacy code and running into a weird error with injector() 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.

like image 992
mr1031011 Avatar asked Dec 25 '22 15:12

mr1031011


1 Answers

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

like image 89
KayakDave Avatar answered Dec 28 '22 05:12

KayakDave