问一个关于requirejs和angularjs加载js文件的问题
发布于 10 年前 作者 coogleyou 16761 次浏览 最后一次编辑是 8 年前

项目使用了requirejs,angularjs,nodejs。。。全部使用requirejs加载js文件,有个问题不明白,直接上代码吧。 我是用angular-gettext对项目的html文件进行国际化,生成了translations.js文件后,angular-gettext官网上的方法是直接在页面引用这个translate.js文件,但是我想使用require.js,通过下面的方式加载,却不成功,我知道是自己没有掌握好requirejs和angularjs的原因,所以想请教怎么做。 大概就是在require.comfig.js中配置require.js,然后gettext是一个angular 的module,translations是用gettext生成的js文件,看代码是属于gettext module的一部分,然后再app.js中,将gettext作为依赖模块,不知道这个translations.js通过requirejs怎么加载??? ###index.js:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <!-- load the root require context -->
    <script src="vendor/require/require.js"></script>
    <script src="app/components/require.config.js"></script>
    <script>require(['app'], function () {})</script>
    <style>
    </style>
  </head>

###require.config.js:

require.config({
  baseUrl: 'app',
  // urlArgs: 'r=[@REV](/user/REV)@',
  paths: {
    config:                   '../config',
    angular:                  '../vendor/angular/angular',
    bootstrap:                '../vendor/bootstrap/bootstrap',
    jquery:                   '../vendor/jquery/jquery-1.8.0',
       'gettext':                '../vendor/angular-gettext',
      //'gettext-trans':          '../vendor/translations'
  },
  shim: {
    angular: {
      deps: ['jquery','config'],
      exports: 'angular'
    },
    bootstrap: {
      deps: ['jquery']
    },
      'gettext':            {
                                deps: ['angular', '../vendor/translations'],
                                exports: 'gettext'
                            },
      //'gettext-trans':      ['angular', 'gettext']
  },
  waitSeconds: 60,
});

###下面是translations.js文件:

angular.module('gettext').run(['gettextCatalog', function (gettextCatalog) {
/* jshint -W100 */
    gettextCatalog.setStrings('zh_Hans', {"Advanced":"高级","Are you sure you want to delete the {{row._id}} 
/* jshint +W100 */
}]);

###angular-gettext文件

angular.module('gettext', []);
angular.module('gettext').constant('gettext', function (str) {
  return str;
});
angular.module('gettext').factory('gettextCatalog', [
  'gettextPlurals',
  '$http',
  '$cacheFactory',
  '$interpolate',
  '$rootScope',
  function (gettextPlurals, $http, $cacheFactory, $interpolate, $rootScope) {
    var catalog;/*不相关的删了*/
    return catalog;
  }
]);
angular.module('gettext').directive('translate', [
  'gettextCatalog',
  '$parse',
  '$animate',
  function (gettextCatalog, $parse, $animate) {
    // Trim polyfill for old browsers (instead of jQuery)
    // Based on AngularJS-v1.2.2 (angular.js#620)
    return {
		/*不相关的删了*/
      }
    };
  }
]).directive('translate', [
  '$compile',
  function ($compile) {
    return {
      restrict: 'A',
      priority: -350,
      link: function (scope, element) {
        var msgstr = element.prop('__msgstr');
        element.html(msgstr);
        $compile(element.contents())(scope);
      }
    };
  }
]);
angular.module('gettext').filter('translate', [
  'gettextCatalog',
  function (gettextCatalog) {
    return function (input) {
      return gettextCatalog.getString(input);
    };
  }
]);
});

###然后是angularjs的入口app.js:

define([
  'angular',
  'jquery',
  'lodash',
  'require',
  'bindonce',
    'gettext',
   // 'gettext-trans'
],
function (angular, $, _, appLevelRequire, gettext) {
  "use strict";
  var app = angular.module('myapp', [gettext]),
    pre_boot_modules = [],
    register_fns = {};
  app.useModule = function (module) {
    if (pre_boot_modules) {
      pre_boot_modules.push(module);
    } else {
      _.extend(module, register_fns);
    }
    return module;
  };
  app.config(function ($routeProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $httpProvider) {
    $routeProvider
      .when('/dashboard', {
        templateUrl: 'app/partials/dashboard.html',
      })
    // this is how the internet told me to dynamically add modules :/
    register_fns.controller = $controllerProvider.register;
    register_fns.directive  = $compileProvider.directive;
    register_fns.factory    = $provide.factory;
    register_fns.service    = $provide.service;
    register_fns.filter     = $filterProvider.register;
  }).run(function(gettextCatalog){
          gettextCatalog.currentLanguage = 'zh_CN';
          gettextCatalog.debug = true;
      });

  var apps_deps = [
    '$strap.directives',
    'ngSanitize',
    'pasvaz.bindonce'
  ];

  // load the core components
  require([
    'controllers/all',
    'directives/all',
    'filters/all'
  ], function () {
    // bootstrap the app
    angular
      .element(document)
      .ready(function() {
        $('html').attr('ng-controller', 'DashCtrl');
        angular.bootstrap(document, apps_deps)
          .invoke(['$rootScope', function ($rootScope) {
            _.each(pre_boot_modules, function (module) {
              _.extend(module, register_fns);
            });
            pre_boot_modules = false;
            $rootScope.requireContext = appLevelRequire;
            $rootScope.require = function (deps, fn) {
              var $scope = this;
              $scope.requireContext(deps, function () {
                var deps = _.toArray(arguments);
                // Check that this is a valid scope.
                if($scope.$id) {
                  $scope.$apply(function () {
                    fn.apply($scope, deps);
                  });
                }
              });
            };
          }]);
      });
  });
  return app;
});
4 回复

不能通过require([‘translations’]) 加载么?

@kingapple translations不是模块。。。

@coogleyou 包装成模块?

@nighca 可以试下:)

回到顶部