javascript 从 JS 外部访问 Angular 对象的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14298361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:15:10  来源:igfitidea点击:

Access Angular object's function from outside JS

javascriptscopeangularjs

提问by Emil

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()):

我正在使用 AngularJS 框架构建一个 HTML 应用程序。我有一些遗留的 JavaScript 操作需要访问 Angular 对象中的函数,但我无法让它工作。
这是 Angular 对象(我需要访问的函数是$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.

我试图通过 访问它angular.element('content').scope().info('me'),但没有结果(控制台说undefined)。我试图转储 的结果angular.element('content').scope(),并获得了完整的对象列表和所有内容。从理论上讲,我的第一个例子应该可以工作,但它没有。

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

非常感谢有关我如何实现这一目标的任何指导!
(PS:从遗留代码调用 Angular JS没有解决这个问题)。



When I was finally able to access the function, it didn't work as expected – the value of $scope.textis technicallymodified, 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.

当我终于能够访问的功能,它并没有如预期的工作-的价值$scope.text技术上的修改,但不更新在HTML中使用的表述!例如,<p>{{text}}</p>从外部函数调用此函数后不会更新。

Is there any way to fix this?

有没有什么办法解决这一问题?

回答by asgoth

angular.element()expects a DOM element, so if you have this html:

angular.element()需要一个DOM 元素,所以如果你有这个 html:

<div ng-controller="content">
</div>

and you want to access its DOM element, use an id:

并且你想访问它的 DOM 元素,使用一个 id:

<div id="myDiv" ng-controller="content">
</div>

Then

然后

angular.element($('#myDiv')).scope().info('me')

or without jQuery:

或不使用 jQuery:

angular.element(document.getElementById('myDiv')).scope().info('me')

should work.

应该管用。

Edit:

编辑:

If you changed something on the scope, you will probably need to use $apply():

如果您更改了范围内的某些内容,则可能需要使用$apply()

angular.element(document.getElementById('myDiv')).scope().$apply();

回答by user1429980

For me, I was trying to access/set angular's values from a callback (in another Window); the solution was to use jQuery's datamethods. The dataAPI allows you to attach object literals to DOM nodes. So instead of resorting to something like global variables (which would also work), I just do something like:

对我来说,我试图从回调(在另一个窗口中)访问/设置 angular 的值;解决方案是使用 jQuery 的data方法。该dataAPI允许你对象文本附加到DOM节点。因此,与其求助于诸如全局变量之类的东西(这也可以),我只是执行以下操作:

/**
 * Listen to a global "lookupTemplate" event
 */
$j(document).on("lookupTemplate", function(event, template) {
        $j(document).data("template", template);
        window.open("/callbackURL", 'Callback Window', 'status=0,toolbar=0,height=230,width=358');
    });

/**
* Callback from other window, to change template ID and name (it's global)
* @param {String} template_id the ID for the selected template from the other window
* @param {String} template_name the name for the selected template from the other window
*/
function templateChosen(template_id, template_name) {
    var template = $(document).data("template");
    var appendedSelector = "[" + template.index + "]";
    $('[name="templateId' + appendedSelector + '"').val(template_id);
    $('[name="templateName' + appendedSelector + '"').val(template_name);
    // Update angular vars just in case
    template.id = template_id;
    template.name = template_name;
}

var app = angular.module("app", []).controller("ActionsController", function($scope) {
        $scope.actions = [];
        $scope.lookupTemplate = function(index) {
            $scope.actions[index].template.index = index;
            $(document).trigger("lookupTemplate", $scope.actions[index].template);
        }
    }
);

Where I increment the nameattribute of each new actionwith the {{index}}helper, included in Angular.

我用助手增加name每个新属性的地方,包括在 Angular 中。action{{index}}