angularjs - RequireJS + AngularJS + 模块 : Dependency issues

标签 angularjs requirejs angular-ui-router angular-google-maps

我在本地设置了 angularjs 应用程序,一切正常,直到我将代码上传到临时服务器。我现在遇到了不受尊重的依赖项问题,但我不明白为什么。我猜它在本地工作,因为它加载库的速度更快。我现在修改了我的应用程序以尝试解决此问题,但无法使其正常工作。

我的应用程序正在加载一个单页应用程序,由 3 个 View (mainmapmap-data)组成。我正在使用 AngularJS 模块结构来启动这个应用程序。这是我的目录结构:

enter image description here

index.html 非常基本:

<!DOCTYPE HTML>
<html lang="en-US">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, minimum-scale=1.0" />
        <title>Map Application</title>
        <link rel="icon" sizes="16x16" href="/favicon.ico" />

        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={{ map_key }}&sensor=false"></script>
        <script type="text/javascript" src="/js/bower_components/requirejs/require.js"></script>

        <link rel="stylesheet" href="/css/main.css" media="screen" type="text/css">
        <link rel="stylesheet" href="/js/bower_components/bootstrap/dist/css/bootstrap.css">
    </head>
    <body>
        <!-- Content -->
        <div id="content" data-ui-view></div>

        <script>
            // obtain requirejs config
            require(['require', 'js/require-config'], function (require, config) {

                // set cache beater
                config.urlArgs = 'bust=v{{ version }}';

                // update global require config
                window.require.config(config);

                // load app
                require(['main']);
            });
        </script>
    </body>
</html>

然后requirejs-config.js:

if (typeof define !== 'function') {
    // to be able to require file from node
    var define = require('amdefine')(module);
}

define({
    baseUrl: 'js', // Relative to index
    paths: {
        'jquery': 'bower_components/jquery/dist/jquery.min',
        'underscore': 'bower_components/underscore/underscore-min',
        'domReady': 'bower_components/requirejs-domready/domReady',
        'propertyParser': 'bower_components/requirejs-plugins/src/propertyParser',
        'async': 'bower_components/requirejs-plugins/src/async',
        'goog': 'bower_components/requirejs-plugins/src/goog',
        'angular': 'bower_components/angular/angular',
        'ngResource': 'bower_components/angular-resource/angular-resource',
        'ui.router': 'bower_components/angular-ui-router/release/angular-ui-router',
        'angular-google-maps': 'bower_components/angular-google-maps/dist/angular-google-maps',
        'moment': 'bower_components/momentjs/moment',
        'moment-timezone': 'bower_components/moment-timezone/moment-timezone',
        'moment-duration-format': 'bower_components/moment-duration-format/lib/moment-duration-format'
    },
    shim: {
        'angular': {
            exports: 'angular'
        },
        'ngResource': ['angular'],
        'ui.router' : ['angular']
    }
});

然后是main.js:

/**
 * bootstraps angular onto the window.document node
 * NOTE: the ng-app attribute should not be on the index.html when using ng.bootstrap
 */
define([
    'require',
    'angular',
    './app'
], function (require, angular) {
    'use strict';

    /**
     * place operations that need to initialize prior to app start here
     * using the `run` function on the top-level module
     */
    require(['domReady!'], function (document) {
        angular.bootstrap(document, ['app']);
    });
});

然后是app.js:

/**
 * loads sub modules and wraps them up into the main module
 * this should be used for top-level module definitions only
 */
define([
    'angular',
    'ui.router',
    './config',
    './modules/map/index'
], function (ng) {
    'use strict';

    return ng.module('app', [
        'app.constants',
        'app.map',
        'ui.router'
    ]).config(['$urlRouterProvider', function ($urlRouterProvider) {
        $urlRouterProvider.otherwise('/');
    }]);
});

在这里您可以看到 app.js 依赖于 ./modules/map/index,我在其中加载所有可用的 Controller :

/**
 * Loader, contains list of Controllers module components
 */
define([
    './controllers/mainCtrl',
    './controllers/mapCtrl',
    './controllers/mapDataCtrl'
], function(){});

每个 Controller 都请求相同类型的模块,这里是mapDataCtrl.js,它是由/触发的:

/**
 * Map Data controller definition
 *
 * @scope Controllers
 */
define(['./../module', 'moment'], function (controllers, moment) {
    'use strict';

    controllers.controller('MapDataController', ['$scope', 'MapService', function ($scope, MapService)
    {
        var now = moment();

        $scope.data = {};
        $scope.data.last_update = now.valueOf();
        $scope.data.time_range = '<time range>';
        $scope.data.times = [];

        var point = $scope.$parent.map.center;

        MapService.getStatsFromPosition(point.latitude, point.longitude).then(function(data){
            $scope.data.times = data;
        });
    }]);
});

如您所见, Controller 正在请求 module.js,其中定义了状态和模块名称:

/**
 * Attach controllers to this module
 * if you get 'unknown {x}Provider' errors from angular, be sure they are
 * properly referenced in one of the module dependencies in the array.
 * below, you can see we bring in our services and constants modules
 * which avails each controller of, for example, the `config` constants object.
 **/
define([
    'angular',
    'ui.router',
    '../../config',
    'underscore',
    'angular-google-maps',
    './services/MapService'
], function (ng) {
    'use strict';

    return ng.module('app.map', [
        'app.constants',
        'ui.router',
        'angular-google-maps'
    ]).config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {
        $stateProvider
            .state('main', {
                templateUrl: '/js/modules/map/views/main.html',
                controller: 'MainController'
            })
            .state('main.map', {
                templateUrl: '/js/modules/map/views/main.map.html',
                controller: 'MapController',
                resolve: {
                    presets: ['MapService', function(MapService){
                        return MapService.getPresets();
                    }],
                    courses: ['MapService', function(MapService){
                        return MapService.getCourses()
                    }]
                }
            })
            .state('main.map.data', {
                url: '/',
                templateUrl: '/js/modules/map/views/main.map.data.html',
                controller: 'MapDataController'
            })
            ;
        //$locationProvider.html5Mode(true);
    }]);
});

我在这个文件中遇到了问题。我正在尝试加载模块 angular-google-maps,因为我需要它在我的 MapCtr Controller 中,并且很可能在 MapDataCtrl 中。但我收到以下消息:

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module app.map due to:
Error: [$injector:modulerr] Failed to instantiate module angular-google-maps due to:
Error: [$inj...<omitted>...1) 

我不知道我错过了什么,对我来说一切看起来都是正确的。我错过了什么?

<小时/>

更新1

我认为这是因为 angular-google-map 不符合 AMD 标准,因此我修改了 requirejs-config.js 如下:

if (typeof define !== 'function') {
    // to be able to require file from node
    var define = require('amdefine')(module);
}

define({
    baseUrl: 'js', // Relative to index
    paths: {
        ...
        'underscore': 'bower_components/underscore/underscore-min',
        'angular-google-maps': 'bower_components/angular-google-maps/dist/angular-google-maps',
        ...
    },
    shim: {
        'angular': {
            exports: 'angular'
        },
        'ngResource': ['angular'],
        'ui.router' : ['angular'],

        'angular-google-maps': {
            deps: ["underscore"],
            exports: 'angular-google-maps'
        }
    }
});

但我仍然遇到同样的问题。

最佳答案

我们可以通过 require.js 来使用 js 库。无需删除 require.js。我仍然需要检查为什么 require.js 配置不起作用。 同时你可以尝试这种方式。

// requirejs-config.js
define({
    baseUrl: 'js', // Relative to index
    paths: {
        'jquery': 'bower_components/jquery/dist/jquery.min',
        'underscore': 'bower_components/underscore/underscore-min',
        'domReady': 'bower_components/requirejs-domready/domReady',
        'propertyParser': 'bower_components/requirejs-plugins/src/propertyParser',
        'async': 'bower_components/requirejs-plugins/src/async',
        'goog': 'bower_components/requirejs-plugins/src/goog',
        'angular': 'bower_components/angular/angular',
        'ngResource': 'bower_components/angular-resource/angular-resource',
        'ui.router': 'bower_components/angular-ui-router/release/angular-ui-router',
        'angular-google-maps': 'bower_components/angular-google-maps/dist/angular-google-maps',
        'moment': 'bower_components/momentjs/moment',
        'moment-timezone': 'bower_components/moment-timezone/moment-timezone'
    },
    shim: {
        'angular': {
            exports: 'angular'
        },
        'ngResource': ['angular'],
        'ui.router' : ['angular']
    }
});
// google-map.js
define(['underscore', 'angular-google-maps'], function(){
});
And then requiring the module each time I need the map:

require(['google-map'], function(){
});

https://github.com/angular-ui/angular-google-maps/issues/390

关于angularjs - RequireJS + AngularJS + 模块 : Dependency issues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23400765/

相关文章:

javascript - 大型 Angular 应用程序的项目结构?

javascript - angular.bind 与 ECMAScript 5 .bind

javascript - 延迟加载: Need JS before HTML render

backbone.js - Requirejs 环境中 Backbone.js ajax 请求的全局错误处理程序

javascript - Ui路由器刷新问题

javascript - AngularJS 指令传递点击操作或执行 ui-router 状态更改

Javascript 上传多个自动生成的文件表单

javascript - 单击指令时图像中的 Angular 淡入淡出

javascript - HTML 页面看不到 AngularJS 模块

javascript - sessionStorage 无法立即可用