【问题标题】:Updating scope from outside AngularJs without using "angular.element.scope"在不使用“angular.element.scope”的情况下从 AngularJs 外部更新范围
【发布时间】:2015-10-07 22:06:14
【问题描述】:

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

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

有谁知道不使用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() 的文档,仅供参考,需要启用调试数据,但出于速度原因,不建议在生产中使用调试数据。以下解决方案似乎围绕 scope() – rtpHarry 2014 年 12 月 5 日在15:12 "

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

AngularJS access scope from outside js function

谢谢!

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

$window.FirstCtrlScope = $scope;

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

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

这是一个好的解决方案,还是有更好的解决方案可以在不使用angular.element(selector).scope 的情况下更新范围?

谢谢!

【问题讨论】:

    标签: javascript jquery angularjs scope


    【解决方案1】:

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

    如果需要配合 jQuery 插件(或其他非 Angular 代码),请将其包装成具有明确 API(属性、绑定和回调)的指令。

    【讨论】:

      【解决方案2】:

      您可以将范围分配给元素上的数据属性,然后访问它。看看here angular-ui-bootstrap 库在哪里实现了这种方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        • 2012-03-08
        • 1970-01-01
        相关资源
        最近更新 更多