简体   繁体   中英

AngularJs : Call controller function bound to 'this' from outside(eg. Browser console)

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM