[英]How to resolve dependencies for a project using AngularJS and RequireJS?
我有一個簡單的AngularJS應用程序,試圖將其重構為使用RequireJS。
由於控制器和服務是異步加載的,因此我不能在index.html
使用ng-app。
以下是我的main.js
require.config({
paths: {
"angular": '../../bower_components/angular/angular',
"angularCookies": '../../bower_components/angular-cookies/angular-cookies'
},
shim: {
angular: {
exports: "angular"
},
angularCookies : {
deps: ["angular"]
}
}
});
require(['angular', './login/js/login'],
function (angular) {
angular.bootstrap(document, ['loginApp']);
}
);
我的login.js
是我定義角度模塊的地方。 以下是我的login.js
'use strict';
define(['angular',
'angularCookies',
'./login.controller'],
function(angular, angularCookies, loginController) {
angular.module('loginApp', [
'ngCookies'])
.config(['$cookiesProvider',
function($cookiesProvider) {
$cookiesProvider.defaults.path = '/';
$cookiesProvider.defaults.domain = 'localhost';
}
])
.run(['$cookies',
'loginService',
function($cookies, loginService) {
}
]).controller(loginController);
});
如圖所示,它依賴於loginController
而loginController
依賴於loginService
。
我的loginService
定義為-
"use strict";
define(['angular',
'angularCookies'],
function (angular, angularCookies) {
var loginService = angular.module('loginApp')
.factory('loginService', [
'$http',
'$cookies',
function ($http, $cookies) {
// My functions and other code here.
}]);
return loginService;
});
使用此配置,我得到一個錯誤- Module 'loginApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Module 'loginApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
我在這里想念什么? 我需要做什么配置才能正確設置?
我看到幾個問題。 首先,不應在登錄中創建該應用。 該應用程序是所有控制器和服務的基礎。
因此,我將把應用程序的創建移到另一個名為app.js
文件中。
然后在我的require config中:
shim: {
'app': {
deps: ['angular', 'angular-route', 'angularCookies']
},
angularCookies : {
deps: ["angular"]
}
}
和:
require
(
[
'app'
],
function(app)
{
angular.bootstrap(document, ['loginApp']);
}
);
然后您的控制器將是:
define(['loginApp'], function(app)
{
app.controller('loginController',
[
'$scope',
function($scope)
{
//...
}
]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.