将angularJS与requireJS配合使用

时间:2014-08-13 13:57:15

标签: angularjs requirejs

我尝试使用requireJS加载angularJS。但我总是遇到这个错误:

  

未捕捉错误:[$ injector:modulerr] http://errors.angularjs.org/1.2.21/ $ injector / modulerr?p0 = phoneApp& p1 =错误%... .org%2F1.2.21%2F%24injector%2Fnomod%3Fp0%3DphoneApp%0A% 20%20%20%20原子%20Err ...... 7)

我已多次检查我的代码,所有脚本都已正确加载,但无法对此错误有所了解。以下是我的代码:

  1. index.html:
  2. <body ng-app="phoneApp">
        <div class="container" ng-controller="PhoneListCtrl">
            <ul>
                <li ng-repeat="phone in phones">{{phone.name}}</li>
            </ul>
        </div>
    </body>
    <script src="bower_components/requirejs/require.js" data-main="scripts/main"></script>
    
    1. main.js
    2. require.config({
          paths : {
              jquery : '../bower_components/jquery/jquery.min',
              angular : '../bower_components/angular/angular.min'
          },
          shim : {
              angular : {
                  exports : 'angular'
              }
          }
      });
      
      require(['jquery', 'angular'],function($, angular){
          angular.module('phoneApp', [])
          .controller('PhoneListCtrl', function($scope){
              $scope.phones = [
                  {'name': 'Nexus S',
                   'snippet': 'Fast just got faster with Nexus S.'},
                  {'name': 'Motorola XOOM™ with Wi-Fi',
                   'snippet': 'The Next, Next Generation tablet.'},
                  {'name': 'MOTOROLA XOOM™',
                   'snippet': 'The Next, Next Generation tablet.'}
              ];
          });
      });
      

1 个答案:

答案 0 :(得分:0)

在您的脚本注册用于引导应用程序的模块之前,HTML会加载。为了使RequireJS与AngularJS一起使用,代码是手动引导您的应用程序。为此,请执行以下操作:

  1. ng-app标记
  2. 中删除body属性
  3. 使用控制器定义模块后,手动引导应用程序,如angular.bootstrap(document, ["phoneApp"])
  4. 请记住,您也可以重复使用其他模块的AngularJS实现,请查看我对此问题的回答:Does it make sense to use Require.js with Angular.js?

    希望这有帮助!