Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Access Angular object's function from outside JS

I'm building a HTML-app with the AngularJS framework. I have some legacy JavaScript actions that needs to access a function within the Angular-object, and I can't get it to work.
This is the Angular-object (function I need to access is the $scope.info()):

function content($scope) {
 $scope.info = function (id) {
 console.log('Got a call from '+id);
 $scope.text = "Hello, "+id;
 };
}

I have attempted to access it through angular.element('content').scope().info('me'), but with no result (console says undefined). I attempted to dump the result of angular.element('content').scope(), and I got the full object list and everything. Theoretically, my first example should work, however it does not.

Any guidance as to how I can achieve this is much appreciated!
(PS: Call Angular JS from legacy code did not resolve this).


When I was finally able to access the function, it didn't work as expected – the value of $scope.text is technically modified, but the expressions used in the HTML are not updated! For example, <p>{{text}}</p>does not get updated after this function is called from an external function.

Is there any way to fix this?

Answer*

Draft saved
Draft discarded
Cancel
9
  • That did work indeed! Though something unexpected happens: the function runs, but if I the function accesses one of the scope's expressions, it does not get updated in the controller. Commented Jan 12, 2013 at 22:38
  • Also, is there any reason this would return Uncaught ReferenceError: $ is not defined when called within a function? Commented Jan 12, 2013 at 22:48
  • Do you have jQuery in your page? Commented Jan 12, 2013 at 22:49
  • if you don't have jquery, try angular.element(document.getElementById('#myDiv')).scope().info('me') Commented Jan 12, 2013 at 22:52
  • 2
    For the non jquery examples, there should be no hash in getElementById('#myDiv') Commented Jan 8, 2015 at 13:42

lang-js

AltStyle によって変換されたページ (->オリジナル) /