Requirejs:仅在需要时加载依赖项

Requirejs: Load Dependancies only when needed

app.js 的定义块中定义的依赖项被加载。

我想做的是:

如果我要加载 Dashboard 控制器,它需要与图表相关的依赖关系,而任何其他控制器都不需要这种依赖关系。

问题: 当应用程序加载时,所有依赖项都被加载,这是我不想要的。

注意:加载依赖项意味着加载js文件。

main.js

require.config({ 
baseUrl: "http://localhost/ums/angular/js",
    paths: {
        'angular': 'lib/angular.min',
        'ngRoute': 'lib/angular-route.min',
        'flash': 'lib/angular-flash',
        'angular-loading-bar': 'lib/loading-bar.min',
        'ngAnimate': 'lib/angular-animate.min',
        'ui.bootstrap': 'lib/ui-bootstrap-tpls-0.12.0',
        'uniqueField': 'admin/directives/angular-unique',
        'input_match': 'admin/directives/angular-input-match',
        'uniqueEdit': 'admin/directives/angular-unique-edit',
        'angularAMD': 'lib/angularAMD.min',
        'googlechart':'lib/ng-google-chart',     
        'app': 'admin/app',
    },
    waitSeconds: 0,
     shim: { 
     'angular': { exports: 'angular'},
    'angularAMD': { deps: ['angular']},
     'googlechart': { deps: ['angular']},
    'ngRoute':{ deps: ['angular']},
    'angular-loading-bar':{ deps:['angular'] },
    'ngAnimate': { deps:['angular'] } ,
    'ui.bootstrap': {deps: ['angular'] },
    'uniqueField': {deps: ['angular'] },
    'input_match': {deps: ['angular'] },
    'uniqueEdit': {deps: ['angular'] },
    'flash': {deps: ['angular'] },
    },
    deps: ['app']
});

app.js

var base_url="http://localhost/ums/";
define(['angularAMD', 'ngRoute','flash','angular-loading-bar','ngAnimate','ui.bootstrap','uniqueField','input_match',  'googlechart'  ], function (angularAMD) {
var app = angular.module('angularapp', ['ngRoute','flash','angular-loading-bar','ngAnimate','ui.bootstrap','uniqueField','input_match' ,  'googlechart'  ]);  
app.config(['$routeProvider', function($routeProvider){
/* *************** routes *************** */
.....

示例控制器:

define(['app'], function (app) {
    app.controller('dashboardCtrl', ['$scope','$http', function($scope,$http){
    //I am able to use any of the dependancy here, (I don't need that all dependancies here )
    //only need charts

        }]); 

 });

在您的情况下,所有依赖项都在创建模块时加载。如果要在控制器时加载它,请将其保留在控制器中并从模块定义中删除。请参阅下面的示例

在您的控制器中

define(['app','googlechart'], function (app) {//charts dependencies
  app.controller('dashboardCtrl', ['$scope','$http', function($scope,$http){
   //I am able to use any of the dependancy here, (I don't need that all dependancies here )
  //only need charts

  }]); 

 });

从模块定义中删除它app.js

 var base_url="http://localhost/ums/";
//remove it from the module definition
define(['angularAMD', 'ngRoute','flash','angular-loading-bar','ngAnimate','ui.bootstrap','uniqueField','input_match' ], function (angularAMD) {
var app = angular.module('angularapp', ['ngRoute','flash','angular-loading-bar','ngAnimate','ui.bootstrap','uniqueField','input_match' ]);  
app.config(['$routeProvider', function($routeProvider){
/* *************** routes *************** */
.....