9

我有一个带有 ASP.NET 应用程序的 iframe,其中包含 UpdatePanel。我开始在应用程序中使用 Angular,但由于 .NET 回发,事情没有奏效。

为了解决这个问题,我使用了这个解决方案:

with (Sys.WebForms.PageRequestManager.getInstance()) {
            add_endRequest(onEndRequest); // regester to the end Request
        }

function onEndRequest(sender, args) {
    angular.bootstrap($('#mainDiv'), ['defaultApp']);
    var rootscope = angular.element('#mainDiv').scope();
    if (rootscope) {
        rootscope.$apply();
    }
}

而且效果很好。

问题是,当我在 ASP.NET 页面中使用另一个 ng-controller 动态加载不同的用户控件时,Angular 会抛出一个错误,指出应用程序已加载:

App Already Bootstrapped with this Element

所以问题是:如何检查应用程序是否已经引导?我可以重新加载这个模块吗?我可以从元素中删除它然后再次引导它吗?

谢谢。

4

2 回答 2

18

从应用程序外部访问范围不是一个好习惯,因此在构建良好的生产应用程序中没有启用它。如果您需要访问/应用范围,那么您的用例有些奇怪/不受支持。

然而,检查一个元素是否已被引导的正确方法是 Angular 库的做法,即加载元素并检查注入器。所以你想要angular.element(document.querySelector('#mainDiv')).injector();哪个使你的代码:

function onEndRequest(sender, args) {
    var element = angular.element(document.querySelector('#mainDiv'));

    //This will be truthy if initialized and falsey otherwise.
    var isInitialized = element.injector();
    if (!isInitialized) {
        angular.bootstrap(element, ['defaultApp']);
    }

    // Can't get at scope, and you shouldn't be doing so anyway
}

您能告诉我们为什么需要应用范围吗?

于 2015-12-28T22:08:10.613 回答
3

您可以简单地检查 的范围mainDiv,如果angular.element(document.querySelector('#mainDiv')).scope()不是undefined,则表示angular尚未初始化。

您的代码将如下所示。

代码

function onEndRequest(sender, args) {
    //below flag will be undefined if app has not bootsrap by angular.
    var doesAppInitialized = angular.element(document.querySelector('#mainDiv')).scope();
    if (angular.isUndefined(doesAppInitialized)) //if it is not 
        angular.bootstrap($('#mainDiv'), ['defaultApp']);
    var rootscope = angular.element('#mainDiv').scope();
    if (rootscope) {
        rootscope.$apply(); //I don't know why you are applying a scope.this may cause an issue
    }
}

更新

在 2015 年 8 月下旬发布 Angular 1.3+ 之后,它通过禁用调试信息来禁用调试信息,从而增加了与性能相关的改进。因此,通常我们应该将 debuginfo 选项启用为 false 以在生产环境中获得良好的性能提升。我不想写太多关于它的内容,因为@AdamMcCormick 的答案已经涵盖了它,这真的很酷。

于 2015-02-09T18:57:08.470 回答