从 JS 外部访问 Angular 对象的函数 [英] Access Angular object's function from outside JS
问题描述
我正在使用 AngularJS 框架构建一个 HTML 应用程序.我有一些遗留 JavaScript 操作需要访问 Angular 对象中的函数,但我无法让它工作.
这是 Angular 对象(我需要访问的函数是 $scope.info()
):
函数内容($scope) {$scope.info = 函数 (id) {console.log('有一个来自'+id的电话);$scope.text = "你好,"+id;};}
我试图通过 angular.element('content').scope().info('me')
访问它,但没有结果(控制台说 undefined代码>).我试图转储
angular.element('content').scope()
的结果,我得到了完整的对象列表和所有内容.理论上,我的第一个例子应该可以工作,但它没有.
非常感谢有关我如何实现这一目标的任何指导!
(PS:从旧代码调用 Angular JS 未解决此问题.
当我终于能够访问该函数时,它没有按预期工作——$scope.text
的值被技术上修改,但使用的表达式在 HTML 中没有更新!例如,<p>{{text}}</p>
在从外部函数调用此函数后不会更新.
有什么办法可以解决这个问题吗?
angular.element()
需要一个 DOM 元素,所以如果你有这个 html:>
并且您想访问其 DOM 元素,请使用 id:
然后
angular.element($('#myDiv')).scope().info('me')
或不使用 jQuery:
angular.element(document.getElementById('myDiv')).scope().info('me')
应该可以.
如果您更改了范围的某些内容,您可能需要使用 $apply():
angular.element(document.getElementById('myDiv')).scope().$apply();
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()
):
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.
Any guidance as to how I can achieve this is much appreciated!
(PS: Call Angular JS from legacy code did not resolve this).
When I was finally able to access the function, it didn't work as expected – the value of $scope.text
is technically modified, 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.
Is there any way to fix this?
angular.element()
expects a DOM element, so if you have this html:
<div ng-controller="content">
</div>
and you want to access its DOM element, use an id:
<div id="myDiv" ng-controller="content">
</div>
Then
angular.element($('#myDiv')).scope().info('me')
or without 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():
angular.element(document.getElementById('myDiv')).scope().$apply();
这篇关于从 JS 外部访问 Angular 对象的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!