javascript - 使 $scope 在非 Angular 函数中可用

标签 javascript angularjs

我有一个带有通用非 Angular JS 函数的实用程序文件。我试图想出一个想法,将当前作用域注入(inject)该文件中的函数中。 我有以下函数可以与 $state 提供程序一起正常工作:

function goToState(state) {
angular.element(document).injector().invoke(function ($state) {
    $state.go(state);
  });
}

但是同样的事情不适用于作用域。我还尝试将 $scope 转换为字符串以发送到函数:

var scopeString = JSON.stringify($scope);

但是得到“将循环结构转换为 JSON”

还有其他想法吗?

谢谢

最佳答案

AngularJS 应用程序中有很多作用域对象。如果您需要向非 AngularJS 代码公开,请使用 $rootScope,它确实是您唯一可以信赖的始终存在的工具。

angular.module("app").run("$rootScope", "$window", function($rootScope, $window) {
    $window.ngRootScope = $rootScope;
});

但请确保每次在 AngularJS 代码之外对该范围执行某些操作时,都将其包装在 $apply() 中。

如果你这样做:

function myNonAngularJSFunction() {
    ngRootScope.someValue = 'newValue';
}

AngularJS 在下次运行摘要循环之前不会知道该值。

相反,这样做可以确保 AngularJS 立即注意到并处理新的范围值:

function myNonAngularJSFunction() {
    ngRootScope.$apply(function(scope) {
        scope.someValue = 'newValue';
    });
}

关于javascript - 使 $scope 在非 Angular 函数中可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916198/

相关文章:

javascript - 当配置依赖于 RequireJS 时使用 RequireJS 配置模块

javascript - 与 CruiseControl、nUnit、nAnt 和 ASP.net MVC 集成的 Javascript 自动化单元测试

ajax - 如何在 Angular 中捕获 http 错误响应

javascript - 如果数据为负,如何更改条形图中条形的颜色 - Angular 图表

angularjs - 无法弄清楚如何使用 $parsers 和 $formatters 创建指令

javascript - 如何从节点和链接列表创建 d3 径向树?

javascript - 在 Meanjs 中,在 bower.json 中添加新库不会自动添加到配置文件中

angularjs - AngularJS 中作用域的继承

javascript - 如何制作拖动条来改变垂直高度?

javascript - 如何在angular js中使用ng-grid和ng-tree?