Angular 直到需要时才找到?

Angular not found until after it's needed?

我们正在尝试使用 Gulp 为一个相当简单的项目设置 Angular,但我们不知何故在第一个障碍上失败了。这是我们设置的,或多或少:

index.html:

<!doctype html>
<html ng-app="testModule">

  <head>
    <meta charset="utf-8">
    <title>Test Module</title>
    <meta name="description" content="">
    <!-- inject:css -->
    <!-- endinject -->
  </head>

  <body>
    <div ng-view></div>

    <!-- inject:js -->
    <script src="/angular-route.js"></script>
    <script src="/angular.js"></script>
    <!-- endinject -->

    <!-- inject:bundle:js -->
    <script src="/bundle.js"></script>
    <!-- endinject -->
  </body>
</html>

bundle.js:

// A bunch of stuff inserted by Gulp.
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';

var angular;

(function () {

    angular.module('testModule', ['ngRoute']);

    angular.module('testModule').config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/foo', {
            template: '<p>Hi.</p>'
        }).otherwise({
            redirectTo: '/foo'
        });
    }]);
})();

},{}]},{},[1])


//# sourceMappingURL=bundle.js.map

这看起来很简单,可以做到万无一失,但这里是我们遇到的错误:

angular-route.js:24:Uncaught TypeError: Cannot read property 'module' of undefined bundle.js:8: Uncaught TypeError: Cannot read property 'module' of undefined angular.js:4458: Uncaught Error: [$injector:modulerr] Failed to instantiate module testModule due to: Error: [$injector:nomod] Module 'testModule' 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.

在处理angular-routebundle时,浏览器似乎并不知道angular的存在,只是后来才知道。我们如何让浏览器更早地检测到 angular 的存在,以便一切正常?

您不需要手动初始化变量angular

这是一个笨蛋,您会注意到我们被带到 /foo 的视图:http://plnkr.co/edit/dxo3ZUJIWLeFw9HXF80w?p=info

  angular.module('testModule', ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/foo', {
            template: '<p>Hi.</p>'
        }).otherwise({
            redirectTo: '/foo'
        });
    }]);