简体   繁体   中英

Typescript AMD and AngularJs - Failed to instantiate module

I'm unsing TypeScript AMD (RequireJs) and AngularJs.

I want to use AMD for my typescript code and not for the rest: jquery, angular, bootstrap, ... For thirdparty js I'm using MVC bundling and I want to continue this way.

This is my thirdparty bundle config:

bundles.Add(new ScriptBundle("~/bundles/thirdparty").Include(
            "~/Scripts/jquery-{version}.js",
            "~/Scripts/bootstrap.js",
            "~/Scripts/respond.js",
            "~/Scripts/require.js",
            "~/Scripts/angular.js",
            "~/Scripts/angular-route.js"
            ));

My _Layout.cshtml is something like:

<!DOCTYPE html>
<html ng-app="PafBase">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    @Scripts.Render("~/bundles/thirdparty")

    <script>
        require.config({
            baseUrl: 'typescript/'
        });
        require(['module/BaseApplication']);
    </script>
</head>
<body>
  @RenderBody()
</body>

BaseApplication.ts is something like:

var app: ng.IModule = angular.module('PafBase', ['ngRoute']); // Breakpoint here ****
app.config(['$routeProvider', ($routeProvider) => { ... }]); 

When run the application I get this javascript error:

[$injector:modulerr] Failed to instantiate module PafBase due to:

Error: [$injector:nomod] Module 'PafBase' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

If I continue the execution I can see that BaseApplication.ts is executed after the angular error.

I think it can be due to angular scan the DOM after ready and found <html ng-app="PafBase"> then search "PafBase" module and not find it due to requireJs don't load BaseApplication.ts before angular scan the DOM.

How to do angular scan the dom after my code is executed?

You can manually bootstrap Angular instead of specifying ng-app="PafBase" . Take a look at the docs here: https://docs.angularjs.org/guide/bootstrap

Basically you just need to remove ng-app from your html and add this to your JS

angular.element(document).ready(function() {
  angular.bootstrap(document, ['PafBase']);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM