Pregunta

(Using requireJS, angularJS, angularAMD)

When in my main.js file I have:

require.config({
    baseUrl: "js",
    paths: {
        'angular': 'libs/angularjs/angular.min',
        'angularAMD': 'libs/angularjs/angularAMD.min'
    },
    shim: {
        'angularAMD': ['angular']
    }
});

define(['angularAMD'], function (angularAMD) {
    var app = angular.module("app", []);
    app.controller("testCtrl", function ($scope) {
        $scope.message = "udało się!";
    });
    angularAMD.bootstrap(app);
    return app;
});

everything works fine. But when I cut config part to other file I got errors:

main.js:

require(['common'], function (common) {
    define(['angularAMD'], function (angularAMD) {
        var app = angular.module("app", []);
        app.controller("testCtrl", function ($scope) {
            $scope.message = "udało się!";
        });
        angularAMD.bootstrap(app);
        return app;
    });
});

common.js

require.config({
    baseUrl: "js",
    paths: {
        'angular': 'libs/angularjs/angular.min',
        'angularAMD': 'libs/angularjs/angularAMD.min'
    },
    shim: {
        'angularAMD': ['angular']
    }
});

Can I use define in require function? If not how to include common config first and then use define?

¿Fue útil?

Solución

I'm assuming your main.js file is what you give to the data-main attribute on the <script> tag that loads RequireJS or that it is the main entry point of your application. Change main.js to this:

require(['common'], function (common) {
    require(['app']);
});

And create an app.js module in a location where your code can readily load it:

define(['angularAMD'], function (angularAMD) {
    var app = angular.module("app", []);
    app.controller("testCtrl", function ($scope) {
        $scope.message = "udało się!";
    });
    angularAMD.bootstrap(app);
    return app;
});

Anything that needs access to the value of app you create in this module can just require the app module.

The code you have in the question defines a module but it does so asynchronously. By the time the call to define happens, RequireJS has already finished loading main. As far as it is concerned, main is done. So what name should it give to the defined module?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top