Search code examples
angularjsgulpangularjs-routing

Angular not found until after it's needed?


We're trying to get Angular set up for a fairly simple project using Gulp, but we're somehow failing at the first hurdle. Here's what we have set up, more or less:

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

This seems simple enough to be foolproof, yet here are the errors we're getting:

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.

It almost seems like the browser doesn't know angular exists when processing angular-route and bundle, and only figures it out later. How can we get the browser to detect the presence of angular earlier so everything works?


Solution

  • You don't need to initialize the variable angular manually.

    Here's a plunker, and you'll note we're brought right to the view for /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'
            });
        }]);