Will Lopez Will Lopez - 5 months ago 44
AngularJS Question

requirejs and angularjs 1.5 injection of ui.router failing for components

I'm getting this error when using the recommended component loading method (See step 3 )

Error: Module name "angular-ui-router" has not been loaded yet for context: _. Use require([])

app module definition:

var adminApp = angular.module('adminClientApp', [require('angular-ui-router'), 'ngMaterial', 'ngResource', 'ngMessages', 'ngMdIcons']);

According to the doco, there isn't a need to include a script tag - it will be loaded via requirejs

Requirejs main.js definition:

'angular-ui-router': 'vendor/angular-ui-router/release/'
'angular': {
exports: 'angular'

app layout:

-- root
-- js
-- app (angular files here)
-- vendor (3rd party libs)

requirejs main.js setting in index.html

<script data-main="main.js" src="vendor/requirejs/require.js"></script>


The guide you are using is not made for RequireJS. After applying the instructions there, you are doing something like this:

  var myApp = angular.module('myApp', [require('angular-ui-router')]);

This will generally fail to work with RequireJS because calling require with a single string fails unless the module is already loaded. This call is guaranteed to work only if it is inside a define, like this:

define(function (require) {
  var myApp = angular.module('myApp', [require('angular-ui-router')]);

This code is a module which should be in a separate .js file and loaded with require(['module name']). (Note that the parameter is an array of strings. This is a different form of require than the one that takes a single string parameter.)

You should use Component, which is what the author of the guide you are using was using when he/she wrote the guide, or a tool that is equivalent to it. Otherwise, you need to convert your code to work with RequireJS.