javascript - 在不使用 "angular.element.scope"的情况下从 AngularJs 外部更新范围

标签 javascript jquery angularjs scope

我希望能够从 Angular 外部的函数更新 Angular 中的范围。

例如,如果我有一个返回成功回调的 jQuery 插件,我希望能够从该成功回调更新范围。我见过的每个解决方案都涉及调用 angular.element(selector).scope,然后在返回的范围上调用 $apply。但是,我也看到很多评论表明这在调试信息关闭时不起作用,因此不推荐这样做,但我还没有看到任何替代解决方案。

有谁知道在不使用 angular.element(selector).scope 的情况下从 Angular 外部更新范围的方法吗?

这是帖子中接受的解决方案:

“如果您想从 AngularJs 的控制之外对范围值进行任何更改,例如 jQuery/javascript 事件处理程序,则需要使用 $scope.$apply()

function change() {
    alert("a");
    var scope = angular.element($("#outer")).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    });
}

这是一个警告,当调试数据在帖子中关闭时 .scope() 不起作用:

“仅供引用,根据使用 .scope() 的文档,需要启用调试数据,但出于速度原因,不建议在生产中使用调试数据。下面的解决方案似乎围绕范围展开( ) – rtpHarry 2014 年 12 月 5 日 15:12“

在这篇文章或其他类似文章中,我没有看到使用 .scope() 的任何替代解决方案。

AngularJS access scope from outside js function

谢谢!

更新 不使用 angular.element(selector).scope 的一种可能解决方案是,我将 Controller 中使用 FirstCtrl 的范围分配给窗口对象。我将 $window 注入(inject)到 FirstCtrl Controller 中并执行了以下操作:

$window.FirstCtrlScope = $scope;

然后我可以从 jQuery 或其他 javascript 做:

var scope=window.FirstCtrlScope;
scope.$apply(function () {
      // update the scope
});

这是一个很好的解决方案还是有更好的解决方案来更新范围而不使用 angular.element(selector).scope

谢谢!

最佳答案

我认为这两种方式都不好。将 Controller 设置为全局变量或通过 html 元素访问范围的设计会导致无法维护的应用程序,其中包含许多隐藏链接。

如果您需要与 jQuery 插件(或其他非 Angular 代码)配合使用,请将其包装到具有清晰 API(属性、绑定(bind)和回调)的指令中。

关于javascript - 在不使用 "angular.element.scope"的情况下从 AngularJs 外部更新范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488464/

相关文章:

javascript - 网格线切换 HMTL5 Canvas

javascript - 在所有其他 javascript 运行之后如何运行 jQuery 函数

angularjs - Selenium Webdriver和angular e2e有什么区别?何时应分别使用?

javascript - 使用绑定(bind)原型(prototype)更改 'this' 的范围

javascript - 菜单总是在顶部和水平滚动

javascript - 不太清楚 JSON 及其在 Angular 上的用途

javascript - 在生成的模板中使用 yeoman-generator 变量

javascript - 带SVG的appendChild在IE9.0中带来了HIERARCHY_REQUEST_ERR(3)

javascript - 错误 SyntaxError : JSON. 解析:JSON 数据后出现意外的非空白字符

javascript - 重定向页面并自动打开一些灯箱