简体   繁体   English

AngularJs:从外部绑定到“ this”的调用控制器函数(例如,浏览器控制台)

[英]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. 我有下面的代码,现在让我们假设我想从外部某个地方调用foo(val)函数,比如说浏览器控制台。

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. 下面的代码仅在foo()绑定到$ scope时有效。

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

Is there any work around or I will be forced to use $scope for this ? 是否有任何解决方法,否则我将不得不为此使用$scope

When controllers are instantiated with "controllerAs" syntax, the this context is bound to the scope property with the specified name: 当使用“ controllerAs”语法实例化控制器时, this上下文将绑定到具有指定名称的scope属性:

<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. 从控制台执行的上述命令将执行与单击Click foo按钮相同的操作。

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. 现在,我可以从任何地方调用window.callFoo()函数。 Seems like it worked as we work with closures in JavaScript. 似乎在处理JavaScript中的闭包时它起作用了。 Still If someone finds a better approach. 仍然,如果有人发现更好的方法。 Please post it here. 请在这里发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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