0

I'm trying to load angularJS with requireJS. But I always encountered this error:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.21/$injector/modulerr?p0=phoneApp&p1=Error%….org%2F1.2.21%2F%24injector%2Fnomod%3Fp0%3DphoneApp%0A%20%20%20%20at%20Err......7)

I have checked my code for many times, all scripts were loaded correctly, but can't get any idea about this error. The below is my code:

  1. index.html:
<body ng-app="phoneApp">
    <div class="container" ng-controller="PhoneListCtrl">
        <ul>
            <li ng-repeat="phone in phones">{{phone.name}}</li>
        </ul>
    </div>
</body>
<script src="bower_components/requirejs/require.js" data-main="scripts/main"></script>
  1. main.js
require.config({
    paths : {
        jquery : '../bower_components/jquery/jquery.min',
        angular : '../bower_components/angular/angular.min'
    },
    shim : {
        angular : {
            exports : 'angular'
        }
    }
});

require(['jquery', 'angular'],function($, angular){
    angular.module('phoneApp', [])
    .controller('PhoneListCtrl', function($scope){
        $scope.phones = [
            {'name': 'Nexus S',
             'snippet': 'Fast just got faster with Nexus S.'},
            {'name': 'Motorola XOOM™ with Wi-Fi',
             'snippet': 'The Next, Next Generation tablet.'},
            {'name': 'MOTOROLA XOOM™',
             'snippet': 'The Next, Next Generation tablet.'}
        ];
    });
});
Allen Li
  • 111
  • 5

1 Answers1

0

What happens is that the HTML loads before yours script register the module used to bootstrap your app. In order to make RequireJS work with AngularJS code is to bootstrap your application manually. To do that, do the following:

  1. Remove ng-app attribute from the body tag
  2. After defining the module with the controller, bootstrap your application manually like this angular.bootstrap(document, ["phoneApp"])

Remember that you could reuse other module's AngularJS implementations too, checkout my answer on this question: Does it make sense to use Require.js with Angular.js?

Hope this helps!

Community
  • 1
  • 1
leog
  • 778
  • 10
  • 15