4
  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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
mr1031011
  • 3,574
  • 5
  • 42
  • 59

1 Answers1

9

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

KayakDave
  • 24,636
  • 3
  • 65
  • 68
  • hi KayakDave, thank you very much for your help. In this case I'm trying to illustrate my situation where I attempt to manipulate the service data outside of angular code (from a legacy code part), which is why I tried to grab the injector using the element. So I guess you are right that the dom has not been constructed yet, perhaps I can simulate by putting my code into a timeout block outside of the controller instead? – mr1031011 Jan 13 '14 at 16:52
  • Any chance it would be ok to have angular call your legacy code and let it know that Angular has finished bootstrapping? – KayakDave Jan 13 '14 at 17:00
  • sure, certainly if angular has a callback upon bootstrapping completion I can surely put that code inside my code. – mr1031011 Jan 13 '14 at 17:02
  • Also, I tried this (with timeout for now). It seems like this time without any error the new value is not updated back into the scope? Do you think I must use watch here? – mr1031011 Jan 13 '14 at 17:03
  • I updated the answer- you don't need a watch but you do need a `scope.$apply` which I added. – KayakDave Jan 13 '14 at 17:42