指令中的AngularAMD加载模块(如下划线)

时间:2015-06-12 15:12:43

标签: javascript angularjs angular-amd

我尝试在我的项目中使用angularAMD模块,使用自定义指令。 在这些指令中,我必须使用外部模块,例如下划线,但我不能仅在指令中加载这些模块。

main.js

require.config({
baseUrl: "app",
paths: {
    'angular': 'vendor/angular.min',
    'angular-ui-router': 'vendor/angular-ui-router.min',
    'angularAMD': 'vendor/angularAMD.min',
    'ngload': 'vendor/ngload.min',
    'underscore': 'vendor/angular-underscore-module',
    'ui-bootstrap': 'vendor/ui-bootstrap.min',
    "jqueryCli": "../assets/js/jquery.min",
    "bootstrapCli": "../assets/js/bootstrap",
    "bootstrapSideCli": "../assets/js/bootstrap-sidebar",
    "underscoreCli": "../assets/js/underscore",
    "mpGrid": "shared/mpGrid/mpGrid",
    "i18nService": "vendor/angular-locale_it-it"
},
shim: {
    'angularAMD': ['angular'],
    'angular-ui-router': ['angular'],
    'underscore': ['angular', 'underscoreCli'],
    'bootstrapCli': ['jqueryCli'],
    'bootstrapSideCli': ['bootstrapCli'],
    'i18nService': ['angular'],
    'mpGrid': ['angular', 'i18nService']
},
deps: ['app']
});

app.js

define(['angularAMD', 'angular-ui-router',
'jqueryCli', 'bootstrapCli', 'bootstrapSideCli', 'underscoreCli',
'shared/sideMenu/sideMenu',
'mpGrid'
], function (angularAMD) {
var app = angular.module("webapp", ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/home");
    $stateProvider
        .state('home',angularAMD.route({
            url: '/home',
            templateUrl: 'home/homeView',
            controller: 'homeCtrl',
            controllerUrl: 'home/homeController'}))
        .state('menu',angularAMD.route({
            url: '/menu',
            templateUrl: 'menu/menuView',
            controller: 'menuCtrl',
            controllerUrl: 'menu/menuController'}));

});
app.constant('appConfig', {
    menu: [
        {value: 'Home', link: '#/home', icon: 'glyphicon-home'},
        {value: 'Menu', link: '#/menu', icon: 'glyphicon-th'}
    ],
    title: 'My Web App'
});
angularAMD.bootstrap(app);
return app;
});

mpGrid.js(我的自定义指令)

define(['angularAMD'], function (angularAMD) {
 angularAMD.directive('mpGrid', ['underscore', function (_) {
     var test = _;
 }]);
});

当我尝试加载视图时,使用mp-grid指令,控制台会显示此错误:

Error: [$injector:unpr] http://errors.angularjs.org/1.4.0/$injector/unpr?
p0=underscoreProvider%20%3C-%20underscore%20%3C-%20mpGridDirective

(与i18nService>相同,<)

任何人都可以帮助我吗?

我疯了:(

1 个答案:

答案 0 :(得分:1)

您需要查看您正在设置的依赖项,首先阅读shim上的文档。

例如,对于underscore中的main.js,您设置:

shim: {
    ...
    'underscore': ['angular', 'underscoreCli'],
    ...
},

您告诉RequireJS加载underscore之前,需要加载angularunderscoreCli

然后,在您的app.js中,加载underscoreCli,它没有依赖项集:

define([..., 'underscoreCli', ... ], function (...) {

另外,仔细检查underscore是否为angular JS包。如果不是,则需要加载它:

define(['angularAMD', 'underscore'], function (angularAMD, _) {
 angularAMD.directive('mpGrid', function () {
     var test = _;
 });
});