来自外部js函数的AngularJS访问范围 [英] AngularJS access scope from outside js function
问题描述
我正在尝试查看是否有一种简单的方法可以通过外部 javascript 函数(与目标控制器完全无关)访问控制器的内部范围
I'm trying to see if there's a simple way to access the internal scope of a controller through an external javascript function (completely irrelevant to the target controller)
我在这里看到了其他几个问题
I've seen on a couple of other questions here that
angular.element("#scope").scope();
将从 DOM 元素中检索范围,但我的尝试目前没有产生正确的结果.
would retrieve the scope from a DOM element, but my attempts are currently yielding no proper results.
这里是 jsfiddle:http://jsfiddle.net/sXkjc/5/
Here's the jsfiddle: http://jsfiddle.net/sXkjc/5/
我目前正在经历从纯 JS 到 Angular 的过渡.我试图实现这一目标的主要原因是尽可能保持我的原始库代码完整;省去了我将每个功能添加到控制器的需要.
I'm currently going through a transition from plain JS to Angular. The main reason I'm trying to achieve this is to keep my original library code intact as much as possible; saving the need for me to add each function to the controller.
关于如何实现这一目标的任何想法?也欢迎对上述小提琴发表评论.
Any ideas on how I could go about achieving this? Comments on the above fiddle are also welcome.
推荐答案
您需要使用 $scope.$apply() 如果您想从 angularjs 控制之外对范围值进行任何更改,例如 jquery/javascript 事件处理程序.
You need to use $scope.$apply() if you want to make any changes to a scope value from outside the control of angularjs like a jquery/javascript event handler.
function change() {
alert("a");
var scope = angular.element($("#outer")).scope();
scope.$apply(function(){
scope.msg = 'Superhero';
})
}
演示:小提琴
这篇关于来自外部js函数的AngularJS访问范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!