RequireJS&烤面包机

时间:2016-05-11 10:10:35

标签: angularjs requirejs

我在使用RequireJS的demoApp中实现Toaster时遇到问题。这里有一些代码:

(function () {
    require.config({
        paths: {
            'angular': 'bower_components/angular/angular',
            'jquery': 'bower_components/jquery/dist/jquery',
            'toaster': 'bower_components/toaster/toaster'
        },
        shim: {
            angular: {
                deps: ['jquery'],
                exports: 'angular'
            },
            toaster: {
                deps: ['angular', 'jquery'],
                exports: 'toaster'
            }
        }
    });

    require([
        'angular',
        'app',
        'toaster',
        'jquery'
    ],
    function (angular, app, toaster) {
        'use strict';
        // toaster is undefined. I add it here just for a check. <<<<<<

        angular.bootstrap(angular.element('body')[0], ['myApp']);
    });
})();

这是main.js,烤面包机是undefined,我在附近写了评论。正如我在控制台的Sources选项卡中看到的那样加载文件。 此外,无论我在哪里使用toaster,都是undefined。这里有一些代码来自同一个演示应用程序:

第一种情况:

define(['somefile', 'toaster'], function (someModule, toaster) {
    'use strict';

    // toaster is undefined

});

第二种情况(John Papa Angular Style Guide):

define(['somefile', 'toaster'], function (someModule) {
    'use strict';

    someModule.controller('NewController', NewController);

    NewController.$inject = ['someDeps', 'toaster'];

    function NewController(someDeps, toaster) {

    // angular.js:13424 Error: [$injector:unpr] 
    // Unknown provider: toasterProvider <- toaster <- NewController

    }
});

以下是我正在使用的内容:

Angular: 1.5.3
RequireJs: 2.2.0
Toaster: 2.0.0

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

您必须区分Angular模块和RequireJS模块。 Toaster仅注册一个Angular模块,无需以RequireJS方式导出任何

shim: {
  // ...
  toaster: {
    deps: ["angular", "jquery"]
  }
}

自举:

require(["angular", "app"], function (angular) {

  // here, app.js is loaded in the DOM, so you can bootstrap Angular:
  angular.bootstrap(angular.element("body")[0], ["myApp"]);

})

在你的app.js中:

define(["toaster" /* , ... */], function () {

  // here, toaster.js is loaded in the DOM, so you can add the "toaster" Angular module in your Angular app dependencies:
  return angular.module("myApp", ["toaster" /* , ... */]);

});

其他地方:

define(["app"], function (app) {

  // as myApp depends on toaster, you can inject the toaster service the Angular way:
  app.controller("MyController", ["toaster", function (toaster) {
    // ...
  }]);

});