从外部JS角访问对象的功能 [英] Access Angular object's function from outside JS
问题描述
我建立一个HTML应用与AngularJS框架。我有一个需要的角度对象中访问一个函数一些遗留的JavaScript动作,我不能得到它的工作。结果
这是角对象(功能,我需要访问的是 $ scope.info()
)
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;
};
}
我已经试图通过 angular.element(内容)来访问它。范围()。信息('我')
,但没有结果(控制台说: 未定义
)。我试图倾倒 angular.element(内容)的结果。范围()
,和我的全部对象列表和一切。从理论上说,我的第一个例子应该工作,但它没有。
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.
任何指导,我怎么能做到这一点是非常AP preciated!结果
<子> (PS:从传统code调用JS角没有解决这一点)。
Any guidance as to how I can achieve this is much appreciated!
(PS: Call Angular JS from legacy code did not resolve this).
当我终于能够访问的功能,它并没有达到预期效果 - 价值 $ scope.text
是技术上的修改,但不更新在HTML中使用的前pressions!例如,&LT; P&GT; {{文本}}&LT; / P&GT;
这个功能是从外部函数调用后没有更新
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()
需要一个 DOM元素,所以如果你有这样的HTML:
angular.element()
expects a DOM element, so if you have this html:
<div ng-controller="content">
</div>
和您要访问它的DOM元素,用一个id:
and you want to access its DOM element, use an id:
<div id="myDiv" ng-controller="content">
</div>
然后
angular.element($('#myDiv')).scope().info('me')
或没有jQuery的:
or without jQuery:
angular.element(document.getElementById('#myDiv')).scope().info('me')
应该工作。
编辑:
如果您在范围改变的东西,你可能需要使用 $适用()
If you changed something on the scope, you will probably need to use $apply():
angular.element(document.getElementById('#myDiv')).scope().$apply();
这篇关于从外部JS角访问对象的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!