AngularJS access scope from outside js function

dk123 picture dk123 · Mar 15, 2013 · Viewed 174.8k times · Source

I'm trying to see if there's a simple way to access the internal scope of a controller through an external javascript function (completely irrelevant to the target controller)

I've seen on a couple of other questions here that

angular.element("#scope").scope();

would retrieve the scope from a DOM element, but my attempts are currently yielding no proper results.

Here's the jsfiddle: http://jsfiddle.net/sXkjc/5/

I'm currently going through a transition from plain JS to Angular. The main reason I'm trying to achieve this is to keep my original library code intact as much as possible; saving the need for me to add each function to the controller.

Any ideas on how I could go about achieving this? Comments on the above fiddle are also welcome.

Answer

Arun P Johny picture Arun P Johny · Mar 15, 2013

You need to use $scope.$apply() if you want to make any changes to a scope value from outside the control of angularjs like a jquery/javascript event handler.

function change() {
    alert("a");
    var scope = angular.element($("#outer")).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    })
}

Demo: Fiddle