0

I have below code, now let's assume I want to call foo(val) function from somewhere outside, let's say browser console.

angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

function MyController() {
    var self = this;
    self.foo = function(val) {
        console.log(val);
    };
    return self;
}

Below code works only when foo() is bound to $scope.

angular.element(document.getElementById('MyController')).scope().foo('Hello');

Is there any work around or I will be forced to use $scope for this ?

Derlin
  • 9,572
  • 2
  • 32
  • 53
Jaspreet Singh
  • 1,672
  • 1
  • 14
  • 21
  • why did you want to do this ? you can also create service and put functions inside it and call them from any other controller/service – AlainIb Mar 29 '17 at 09:02
  • http://stackoverflow.com/questions/13743058/how-do-i-access-the-scope-variable-in-browsers-console-using-angularjs?rq=1 – AlainIb Mar 29 '17 at 09:03
  • There is no other way (at least without global variables) – Derlin Mar 29 '17 at 09:05
  • @Derlin Could you please check if the work around I posted is a decent approach for this situation. – Jaspreet Singh Mar 29 '17 at 12:47
  • again, why would you need to access the variable outside without the call to `scope()` ? Your workaround could work, but could also cause problem (see ste2425's comment) – Derlin Mar 29 '17 at 12:58

2 Answers2

1

When controllers are instantiated with "controllerAs" syntax, the this context is bound to the scope property with the specified name:

<div id="MyController" ng-controller="MyController as vm">
    <button ng-click="vm.foo()">
        Click foo
    </button>
</div>
$scope = angular.element(document.getElementById('MyController')).scope()

$scope.vm.foo('Hello');
$scope.$apply();

The above commands executed from the console will do the same action as clicking the Click foo button.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

Found a work around :

angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

function MyController() {
    var self = this;
    self.foo = function(val) {
        console.log(val);
    };
    window.callFoo = function(val) {
        self.foo(val);     
    }
    return self;
}

Now I am able to call this window.callFoo() function from anywhere. Seems like it worked as we work with closures in JavaScript. Still If someone finds a better approach. Please post it here.

Jaspreet Singh
  • 1,672
  • 1
  • 14
  • 21
  • Don't know if this is angular 2, but in angular 1 this can easily cause bugs. If a digest cycle isn't running and you executed your exposed method no data-binding will happen unless you manually run a digest cycle. (Its happened out of angular's knowing). If you manually run a digest cyle whilst one is already running it will throw an exception. – ste2425 Mar 29 '17 at 12:50